48 Commits

Author SHA1 Message Date
bhursey 07cd913c8b Record the two-wide raw import in the 0.5.4.1 notes
CI / verify (push) Has been cancelled
The reissued 0.5.4.1 artifacts no longer import raws four at a time, so the
release notes and the measurements behind the change belong in that section.
2026-12-02 17:36:48 +00:00
bhursey 3b288bc03b Republish the 0.5.4.1 artifacts with the two-wide raw import
Windows setup, portable zip, Ubuntu tar.gz and deb rebuilt from bd90264, with
the checksums the release page now lists.
2026-12-02 17:31:20 +00:00
bhursey bd90264c3c Hold raw imports to two files in flight
A raw upload request stays open for the whole decode, and four X-Trans frames
decoded together took 87-102 s each on a 12-core server against 28 s alone, so
every request outlived a 60 s reverse-proxy read timeout and came back as 504
while the server was still working. Two-wide keeps a request near 45 s and
finishes a 16-file batch sooner as well; Bayer files give up a little.
2026-12-02 17:21:14 +00:00
bhursey 8f23e96b92 Republish the 0.5.4.1 Windows build with the launcher fix
The setup and portable zip are rebuilt from the tree that reads the machine
architecture instead of the process's, so the finish-page launch no longer
refuses 64-bit Windows. Checksums updated for both artifacts.
2026-12-02 16:31:03 +00:00
bhursey 5f15b528f4 Read the machine architecture, not the process's, in the launcher
The platform check read PROCESSOR_ARCHITECTURE, which a WOW64 process reports as
x86. Starting Luminary from the setup's finish page therefore stopped on 64-bit
Windows with "Luminary ships a 64-bit runtime; this PC reports 'x86'". The
machine architecture now comes from PROCESSOR_ARCHITEW6432 and
Is64BitOperatingSystem.
2026-12-02 16:23:12 +00:00
bhursey 5b4b49200c Grade preset previews over the current edit and print the look's cast
Preset tiles were rendered from a reset grade, so correcting a frame and then
browsing looks showed thumbnails that no longer matched the canvas, and the
settle timer was keyed on object identity so the rail rarely caught up at all.
Tiles now render the whole grade a moment after it settles, keep their previous
images while the batch re-renders, and the Light panel shows the applied look's
cast and the final white balance under Temp and Tint.
2026-12-02 05:27:12 +00:00
bhursey 4d7a123d49 Start Luminary from the setup's finish page through the shell
MUI2 runs the finish-page target with Exec, which passes the path straight to
CreateProcess. The 0.5.4.1 bundle ships the PowerShell launcher, so that target
is Luminary.vbs and the ticked "Start Luminary" box closed the installer without
opening anything. ExecShell goes through the shell, so the .exe, .vbs and .cmd
all start. The 0.5.4.1 setup is rebuilt from the same staged bundle, so the
portable zip keeps its hash.
2026-12-02 04:52:57 +00:00
bhursey df447794ea Match the 0.5.4.1 notes to the build that shipped
The entry still described raws importing two at a time and claimed the
build was never published, and it listed the offline audit and object
removal, which are not in the artifacts. Record the four-wide window, the
worker-thread colour pass, the published links and the new hashes; move
the unshipped work to its own section.
2026-12-02 04:16:11 +00:00
bhursey d24cbf26b8 Run the camera-to-sRGB pass on a worker thread
At four parallel imports the synchronous colour conversion was the widest
serial section left in the pipeline. The frame buffers now live on
SharedArrayBuffer, so a worker writes the same memory the encoder reads
and the main thread is free for the decoder pool and zlib.
2026-12-02 04:02:33 +00:00
bhursey 7f0838156b Write ratings, keywords, hierarchy and IPTC to XMP
Sidecars and JPEG exports now carry xmp:Rating, xmp:Label, dc:subject and
lr:hierarchicalSubject plus the IPTC core, and importing a sidecar applies its
cataloguing fields independently of its develop settings. Hierarchical keywords
keep leaf terms in the flat list, so search and filters are unchanged.
2026-12-02 03:30:57 +00:00
bhursey fa0a7e64ef Speed up raw imports and add a per-import 16-bit toggle
Import raws four at a time to match the decoder pool, compress the 16-bit
sidecar with RLE on the libuv pool, and demosaic X-Trans files in a single
Markesteijn pass so Fuji imports no longer queue into decode timeouts. The
import dialog now offers 16-bit (default) or 8-bit per import, sent as
`?sidecar=0`, and the camera thumbnail and embedded-preview fallbacks no
longer drop to 8-bit samples or store a 0x0 photo.
2026-12-02 03:25:53 +00:00
bhursey ea7b5b846c Install remote dependencies before deploying builds
CI / verify (push) Has been cancelled
The rsync excludes node_modules, so a new dependency in the lockfile made the
remote build fail until someone installed it by hand. Run npm ci on the server
first and stop with the installer's exit code if it fails.
2026-12-01 15:27:17 +00:00
bhursey e7e1d16242 Build the 0.5.4 Windows bundles
Zip and installer carry the JXL wasm codec, the regenerated guide and the
native WebView2 window.
2026-12-01 15:13:20 +00:00
bhursey 68f074452c Build the 0.5.4 Linux bundles
Linux smoke test passes, including the offline import path.
2026-12-01 14:58:33 +00:00
bhursey c5d5d6598d Release 0.5.4 with JPEG XL export
Bumps the version, moves the changelog entry out of Unreleased, updates the
guide to version 1.3 and regenerates its PDF, and records the security audit
in the release notes.
2026-12-01 14:56:40 +00:00
bhursey 9ea4c03d65 Rebuild the Windows bundles with JPEG XL export
The zip and installer now carry the JXL wasm codec and the regenerated user
guide, with the native WebView2 window unchanged.
2026-12-01 14:50:10 +00:00
bhursey 326282476f Rebuild the Linux bundles with JPEG XL export
The tar and deb now carry the JXL wasm codec and the regenerated user guide.
2026-12-01 14:44:41 +00:00
bhursey 3759b47bc6 Add JPEG XL export with a lossless option
Export now offers JPEG XL (8-bit sRGB) next to JPEG, PNG, WebP and 16-bit
TIFF, encoded on-device by libjxl compiled to WebAssembly so the export stays
offline. The codec loads only when a JXL is chosen, the quality slider applies
to the lossy mode, and a lossless switch disables it. The user guide and
changelog describe the format and its current limits (no ICC or XMP yet).

Also adds SECURITY-AUDIT.md with the dependency scan and the review of the
server's trust boundaries.
2026-12-01 14:43:29 +00:00
bhursey 8b309d9cad Publish the 0.5.3.1 Windows artifact checksums 2026-12-01 13:31:18 +00:00
bhursey 8fba0835b9 Publish the 0.5.3.1 Linux artifact checksums 2026-12-01 13:26:05 +00:00
bhursey 83322d9b50 Describe the desktop app and the local engine in the user guide
The guide still read as a team-server product: raws were "sent to the server"
and the Windows chapter described the old Program Files install. It now explains
the local engine, the native window, offline start and the per-user installer,
and the PDF is regenerated from it.
2026-12-01 13:25:05 +00:00
bhursey 7282d2d960 Publish the 0.5.3.1 Windows artifact checksums 2026-12-01 13:20:25 +00:00
bhursey 5cc8867878 Publish the 0.5.3.1 Linux artifact checksums 2026-12-01 13:14:06 +00:00
bhursey 93168de914 Document the 0.5.3.1 desktop release and add a changelog
The README described only the browser and team-server modes, so the desktop
bundles, their offline behaviour and the native Windows window were undocumented,
and there was no changelog to point testers at.
2026-12-01 13:12:50 +00:00
bhursey 970fa18d86 Publish the 0.5.3.1 Windows artifact checksums 2026-12-01 13:09:36 +00:00
bhursey a4aa43461f Ship the native app window and start from Luminary.exe
A tester saw Edge open and start syncing his Microsoft account; the bundle
carried no WebView2 host, so the launcher fell back to Edge's app mode. The
window host is now built and shipped, the fallback prefers Chrome over Edge, and
the installer's Start Luminary, shortcuts and start-at-login use Luminary.exe so
they no longer depend on Windows Script Host, which policy can disable.
2026-12-01 13:04:37 +00:00
bhursey 9aff70bd63 Publish the 0.5.3.1 Windows artifact checksums 2026-12-01 12:53:13 +00:00
bhursey bbcf2efda6 Publish the 0.5.3.1 Linux artifact checksums 2026-12-01 12:48:29 +00:00
bhursey f1f96f1f10 Check offline imports in the smoke tests
With the network down, a request that goes through the system proxy cannot
reach 127.0.0.1, which is how a healthy engine looked unreachable. Both smoke
tests now start under a proxy pointed at a black hole, import a TIFF through the
real upload and preview path, and assert the launcher and app window bypass
proxies.
2026-12-01 12:47:06 +00:00
bhursey 0525e496e0 Say local engine in the import dialog and the offline errors
A tester saw "raw files are demosaiced by the server" and read it as an upload
to someone else's machine. In desktop mode the decoder runs in the bundle on
this PC, so the import dialog, the join page and the "cannot reach" error now
say local engine, while team-server installs keep the server wording.
2026-12-01 12:45:04 +00:00
bhursey 91ce88a51f Publish the 0.5.3.1 Windows artifact checksums 2026-12-01 12:38:15 +00:00
bhursey b675fa8fea Publish the 0.5.3.1 Linux artifact checksums 2026-12-01 12:32:31 +00:00
bhursey 2d3b3bb665 Call the local process the local engine on Linux and macOS
The Windows launcher already avoids the word "server" in what users read, and
the macOS health probe now uses curl --noproxy so starting offline cannot stall
on a system proxy. The app windows also ignore proxies, which only ever point
at 127.0.0.1.
2026-12-01 12:31:10 +00:00
bhursey b271037c54 Publish the 0.5.3.1 artifact checksums 2026-12-01 12:24:37 +00:00
bhursey afdbeb4283 Say background service instead of network service
"Network service" still reads as something that talks to the internet. The
generated bundle README now calls the local engine a background service on this
PC and says a connection is not needed.
2026-12-01 12:24:37 +00:00
bhursey e7ecd712e2 Create the NSIS cache directory on a fresh build
--installer unpacks a private NSIS into <out>/tools/nsis, but dpkg-deb creates
only the leaf directory, so the build failed whenever --out had no tools/ yet.
The parent is created first.
2026-12-01 12:24:37 +00:00
bhursey 7eac7e7ecf Release 0.5.3.1
Ships the offline-start fix for the Windows launcher and the before/after split.
2026-12-01 12:14:31 +00:00
bhursey 7cad990c8e Call the local process the local engine, not a server
Windows users read "server" as a network service and asked whether the app
phones home, even though the bundle only ever talks to 127.0.0.1. The launcher
dialogs, the help text, the Stop shortcut and the bundle README now call it the
local engine and say plainly that it is a background process on this PC.
2026-12-01 12:14:31 +00:00
bhursey a7ba0d2e87 Start the Windows bundle when the network is disconnected
The launcher asked /api/health through Invoke-WebRequest, which resolves the
system proxy or PAC script before it looks at the URL; with no network every
probe timed out and the launcher killed a healthy local process after two
minutes and reported that Luminary had not started. Both launchers now probe
127.0.0.1 over a raw TCP socket, which uses no proxy, DNS or certificate store,
and the app window is started with --no-proxy-server.
2026-12-01 12:13:54 +00:00
bhursey 7aef2e37bf Add a before/after split with a draggable handle
The Develop preview can put the untouched source left of a drag line and the
edited frame right of it. Both halves come from one render on one view, so they
line up exactly, and the split shares its handle behaviour with the lens
correction split. The headless render check now asserts that each half shows its
own edit.
2026-12-01 12:13:54 +00:00
bhursey b39cad02fe Read the app version from package.json everywhere
CI / verify (push) Has been cancelled
The version was duplicated in the server, the About panel and the release
scripts, and had already drifted once. The server health endpoint and the
About panel now take it from package.json, and the help sheet gained an
About section that shows the version alongside the guide details.
2026-12-01 06:02:16 +00:00
bhursey 5cde6d444b Publish the 0.5.2 artifact checksums
CI / verify (push) Has been cancelled
The Linux and Windows builds were rerun after the health endpoint moved to
0.5.2, so their SHA-256 sums changed.
2026-12-01 05:38:30 +00:00
bhursey 74a16fbf88 Report 0.5.2 from the health endpoint
The server carries its own copy of the version for /api/health, which was left
behind when the packages moved to 0.5.2 and made a deployed build look older
than it is.
2026-12-01 05:31:27 +00:00
bhursey becfafc603 Skip the ONNX CUDA download in the Windows build image
CI / verify (push) Has been cancelled
The cross-build container runs npm ci against the host package.json, which
otherwise pulls the CUDA runtime the bundle never loads.
2026-12-01 05:27:46 +00:00
bhursey 4758fa1076 Release 0.5.2
Bumps the app version so the packages carry the SCUNet and NLM denoise bases,
and updates the packaging docs to the new filenames.
2026-12-01 05:18:59 +00:00
bhursey b633f07042 Keep experiments out of the Docker build context
spike/ held a 449 MB set of ONNX trials and .pi/ session notes, both of which
were being copied into every image build. Neither is referenced by the app, so
ignore them alongside the existing scratch directories.
2026-12-01 04:16:52 +00:00
bhursey f7942d0bd0 Offer SCUNet and NLM alongside the guided denoise
The AI denoise panel now picks between three bases: the existing guided
filter, non-local means and a learned SCUNet model run through
onnxruntime-node on overlapping tiles. The base is part of the render key, so
each model keeps its own cached render and switching back is instant, and jobs
report stage and tile progress instead of a bare spinner.

onnxruntime-node is pinned to 1.23.0, the last release that ships both macOS
architectures, and every Docker and desktop install skips its CUDA download
because only the CPU binaries in the package are used. The SCUNet weights and
ONNX Runtime are added to the third-party notices, the deb copyright file and
the README's denoise, API and redistribution sections.
2026-12-01 04:03:53 +00:00
bhursey b34d34dacb Package a self-contained macOS app and harden serving
- Add macos/build.mjs: stages a universal .app outside the checkout, bundles
  and checksums Node, installs production deps per architecture, compiles the
  launcher shim, signs ad-hoc or with a Developer ID, and writes a zip and dmg
  with an optional notarization path.
- Serve precompressed brotli/gzip assets and split admin panels and the public
  pages out of the main bundle.
- Support HTTP range requests, and fix upload and quota accounting, gallery
  download counts and unreadable-file handling.
- Add server HTTP integration tests, a Gitea CI workflow, a catalog backup
  script and a crash screen for the UI.
2026-11-29 06:23:58 +00:00
95 changed files with 6462 additions and 582 deletions
+3
View File
@@ -6,6 +6,9 @@ docs
server/data server/data
.check .check
.smoke .smoke
# Experiments and session notes: hundreds of MB that no image needs
spike
.pi
*.log *.log
.DS_Store .DS_Store
README.md README.md
+36
View File
@@ -0,0 +1,36 @@
# Verification pipeline for git.maple-street.net (Gitea Actions / act_runner).
#
# Runs the same gates a release needs, so a broken commit cannot reach main
# unnoticed. The container is pinned to the Node major the Dockerfile ships, and
# the runner only needs Docker — no Node, Chrome or extra tools on the host.
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
verify:
runs-on: ubuntu-latest
container: node:24-bookworm
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install dependencies
run: npm ci
- name: Typecheck
run: npm run typecheck
# Includes the server HTTP suite, which starts the real server against a
# temporary data directory (auth, ownership, quota, gallery, ranges).
- name: Tests
run: npm test
- name: Production build
run: npm run build
- name: Server syntax
run: for file in server/*.mjs; do node --check "$file"; done
+8
View File
@@ -15,6 +15,11 @@ server/data/
*.log *.log
.DS_Store .DS_Store
# Experiments and session notes that never ship
spike/
.pi/
HANDOFF-*.md
# Windows native-window build output # Windows native-window build output
windows/launcher/webview2/bin/ windows/launcher/webview2/bin/
windows/launcher/webview2/obj/ windows/launcher/webview2/obj/
@@ -22,3 +27,6 @@ windows/launcher/webview2/obj/
# Transfer-only Windows release archives # Transfer-only Windows release archives
windows/releases/*.zip windows/releases/*.zip
windows/releases/*.exe windows/releases/*.exe
# Transfer-only macOS release archives
macos/releases/
+209
View File
@@ -0,0 +1,209 @@
# Changelog
Dated release notes, newest first. The same entries are summarised on the product
page; this file is the complete list.
## Unreleased
Finished in the tree, not part of any build yet.
- **Film looks and presets grade over your white balance.** Applying a look used
to overwrite Temp and Tint with the stock's own numbers, so a frame that had
been corrected came back with the look's cast on an uncorrected image. The
cast is now kept apart from the sliders and applied after your correction; it
layers on instead of replacing it, and switching looks swaps the cast rather
than stacking them. Every preset tile now renders over the photo's whole
current grade — exposure, tone, colour, crop and white balance — so a
thumbnail is what the click produces, and the rail keeps its images while the
tiles catch up. The Light panel reports the applied look's cast and the final
balance the photo is graded at, under Temp and Tint.
- **An audited offline guarantee.** A content security policy restricts connections to
the app's own origin, `npm run check:offline` fails the build if any shipped file
reaches for another host, and [docs/OFFLINE-GUARANTEE.md](docs/OFFLINE-GUARANTEE.md)
states what the app does and does not contact.
- **Object removal on the server** (`POST /api/photos/:id/inpaint`, LaMa, Apache-2.0,
bundled weights, no network). The routes and the cached-render store are in place;
there is no editor control for it yet, so nothing changes for a user.
## 0.5.4.1 — 2 December 2026
Windows patch on 0.5.4 for the Fujifilm import report, plus the metadata work that was
finished after 0.5.4. The installer and portable zip are linked from the download page
alongside 0.5.4; macOS remains at 0.5.1.
### Fixed
- **The launcher no longer rejects a 64-bit PC started from a 32-bit parent.**
The platform check read `PROCESSOR_ARCHITECTURE`, which a WOW64 process reports
as `x86`. Starting Luminary from the setup's own finish page (a 32-bit NSIS
process) therefore stopped at "Luminary ships a 64-bit runtime; this PC reports
'x86'" on ordinary 64-bit Windows. It now reads the machine architecture from
`PROCESSOR_ARCHITEW6432` and `Is64BitOperatingSystem`, so launch context no
longer changes the answer.
- **The setup now starts Luminary when "Start Luminary" is ticked.** The finish
page ran the launcher with NSIS `Exec`, which passes the path straight to
`CreateProcess`. This build ships the PowerShell launcher, so the target was
`Luminary.vbs`, a script `CreateProcess` cannot start: the box was ticked, the
installer closed and no window opened. It now goes through the shell
(`ExecShell`), which starts the `.exe`, `.vbs` and `.cmd` alike. The 0.5.4.1
setup was rebuilt from the same staged bundle; the zip is unchanged.
- **Fujifilm imports are about five times faster.** LibRaw was asked for three
Markesteijn demosaic passes on X-Trans sensors; on a 40 MP X-T5 frame that took
**49.9 s**, and one pass takes **8.8 s** with no visible difference in the 6000 px
proxy the editor works on. X-Trans files are detected from the camera make and model
after the cheap header read, and demosaic at one pass
(`LUMINARY_RAW_XTRANS_QUALITY`, 1–3); Bayer files keep their previous setting. A full
40 MP decode fell from 44–50 s to about 20 s including the 16-bit sidecar.
- **A raw can no longer be saved as an unopenable 0×0 photo.** When decoding failed or
timed out, the fallback scanned the container for a JPEG and could stop at a nested
EXIF thumbnail's end marker, then store the truncated bytes anyway, with width and
height 0. It now tries every embedded candidate largest-first and keeps the first one
that actually decodes, so a hard file imports from the camera's own preview instead.
The import no longer trusts a server-reported `0` for a dimension either.
- **A wide selection no longer fails in waves.** The decode timeout used to start when
the request arrived and therefore counted time spent queued for a worker, and a
timed-out decoder was returned to the pool while still busy with the abandoned job —
four parallel Fuji files produced four timeouts and four broken previews. The clock now
starts when a worker picks the job up, and a timed-out worker is discarded.
- **Progress starts with the import.** The bar was only updated when a file finished, so
a 16-file Fuji import showed nothing for the first minute and then jumped to 4/16. It
now reports before each file starts, names the file, and says how many are still
waiting (`7 / 16 · 9 waiting · DSCF1024.RAF`).
- **The 16-bit sidecar no longer blocks previews.** Its PNG is compressed off the main
thread, so the editor stays responsive while an import runs.
### Changed
- **Raws import two at a time.** A raw upload request stays open for the whole decode,
and four 40 MP X-T5 frames decoded together took 87–102 s each on a 12-core server
against 28.4 s alone — long enough for a 60 s reverse-proxy read timeout to answer 504
while the server was still working, which reads as the last files of a batch failing.
Two-wide holds a request near 45 s and finishes sixteen files sooner (~360 s against
~410 s); Bayer files give up a little. Camera JPEGs and PNGs still import four at a
time, because the browser decodes those itself. This build reissues 0.5.4.1 with the
window reduced from four; the setup, zip, tar.gz and .deb were rebuilt for it.
- **The camera-to-sRGB pass runs on a worker thread.** It was the widest synchronous
section left in a decode, and four parallel imports queued behind it on the event
loop. The frame buffers are now allocated on `SharedArrayBuffer`, so a worker writes
the same memory the encoder reads and nothing is copied across the boundary; frames
that arrive unshared fall back to the previous synchronous path.
### Also in this build (finished after 0.5.4)
- **Hierarchical keywords, IPTC and portable ratings.** Keywords can be grouped as paths
(`Wedding > Ceremony > Rings`) with suggestions from what is already in the catalog,
the IPTC fields are editable in the metadata panel, and star ratings and colour labels
are written to XMP (`xmp:Rating`, `xmp:Label`) alongside `dc:subject` and
`lr:hierarchicalSubject`, so they survive a round trip through Lightroom or Bridge.
### Notes
- Windows only. `Luminary-0.5.4.1-win-x64-setup.exe` and the portable zip are built
locally and published as links on the download page, with their SHA-256 sums in
`windows/releases/SHA256SUMS.txt`.
## 0.5.4 — 1 December 2026
Windows and Linux bundles rebuilt with the new export format. macOS remains at
0.5.1 because it has to be built on a Mac.
### Added
- **JPEG XL export.** The export dialog offers JPEG XL alongside JPEG, PNG, WebP and
16-bit TIFF, with the quality slider and a lossless switch. Files are 8-bit sRGB,
encoded by libjxl compiled to WebAssembly in the app itself, so the export stays
offline and nothing is uploaded. The codec loads only when a JXL is exported. No
ICC profile or XMP metadata is embedded yet, and 16-bit JXL waits on a float-input
encoder build. The codec is Apache-2.0 and makes no network requests.
### Security
- **Static security audit published** as [SECURITY-AUDIT.md](SECURITY-AUDIT.md):
dependency scan plus a review of authentication, authorisation, uploads, path
handling, secrets at rest and outbound requests. No exploitable issue was found
in code that ships; the two production advisories are a transitive `adm-zip`
inside `onnxruntime-node` that this application cannot reach.
## 0.5.3.1 — 1 December 2026
Windows and Linux bundles rebuilt. macOS stays at 0.5.1: the app has to be built on
a Mac with the Xcode command line tools, and no Mac was available.
### Added
- **Before/after split** in Develop: a draggable handle compares the edited frame
with the untouched source, alongside the existing hold-`\` full-frame preview.
- **Native Windows window.** Windows bundles now ship `LuminaryWindow.exe`, a
WebView2 window host built from `windows/launcher/webview2` (.NET 8, self-contained
win-x64). The app opens its own window: no browser process, no Edge profile, no
Microsoft account and no settings sync. If the WebView2 runtime is missing, the
window says so and links to the one-time download.
- **Offline import checks in both smoke tests.** `linux/SMOKE-LINUX.sh` and
`windows/SMOKE-WINDOWS.ps1` now start under a proxy pointed at a black hole, import
a TIFF through the real upload → decode → preview path, and assert the launcher and
app window bypass proxies, so a bundle cannot regress to proxy-routed loopback
requests.
### Changed
- **The local process is called the local engine**, not "the server", everywhere a
user reads it: the Windows, Linux and macOS launchers, the import dialog, the join
page and the "cannot reach" error. Team-server installs keep the server wording.
- The import dialog states that raws are demosaiced by the local engine on this PC and
that nothing leaves the computer, instead of implying an upload.
- The Windows fallback app window prefers Chrome over Edge.
- The installer's **Start Luminary** tick, the Start-menu and desktop shortcuts and
start-at-login run `Luminary.exe` instead of `Luminary.vbs`, so they no longer depend
on Windows Script Host — which group policy can disable, leaving the tick silently
doing nothing. `.vbs` and `.cmd` remain fallbacks for bundles without the native
launcher.
- Downloads describe the network need as `Network: not needed` and the process as a
background service on this PC.
### Fixed
- **The Windows bundle starts with the network disconnected.** The launcher waited for
`/api/health` with `Invoke-WebRequest`, which resolves the system proxy/PAC before
the URL; offline, every probe failed and the launcher killed a healthy engine after
120 seconds. The probe is now a raw TCP request to `127.0.0.1`, the Go launcher uses
a loopback-only transport, and app windows start with proxies disabled.
- The macOS launcher probes with `curl --noproxy '*'` for the same reason.
- A fresh Windows build creates the NSIS cache directory before extracting the
compiler, instead of failing on the first run.
### Notes
- macOS 0.5.3.1 is not built yet. On a Mac:
`git pull && node macos/build.mjs --arch universal --node v22.23.5 --publish`.
- Screenshots and the bundled user guide still describe the team-server workflow; they
are being brought in line with the single-user desktop app.
## 0.5.2 — 1 December 2026
- AI denoise offers three models: Guided (fastest), SCUNet (learned, removes the most
grain) and NLM, each cached separately so switching back to one already rendered is
instant.
- The panel reports the stage it is in and, for SCUNet, the tile count while a render
runs instead of leaving a blank spinner.
- The bundles carry the SCUNet weights and ONNX Runtime, so the downloads are larger
than 0.5.1: the Windows setup is 165 MB and the Ubuntu `.deb` is 182 MB.
- The macOS build stays at 0.5.1.
## 0.5.1 — 28 November 2026
- Direct window launches use the PowerShell launcher instead of Windows Script Host,
fixing the direct-launch failure on systems where VBScript is disabled.
- A `.deb` for Ubuntu 22.04 and 24.04 ships alongside the Windows build: same app, same
server, menu entry included.
- A Windows setup exe installs per user with Start-menu shortcuts and keeps the catalog
when uninstalled; the portable ZIP still ships for people who want a folder.
## 0.5.0 — 28 November 2026
- First public beta: browser library, raw editor and Windows app.
- Directly opening the Windows window hands off to the launcher, so desktop mode stays
signed in.
- Masks, lens correction, print layouts and batch export.
- Client galleries with picks, comments and change requests.
- Optional team server for accounts, shared storage and admin.
- Refreshed product site and a 39-page user guide with current screenshots.
+8 -1
View File
@@ -4,6 +4,10 @@
FROM node:24-bookworm-slim AS deps FROM node:24-bookworm-slim AS deps
WORKDIR /app WORKDIR /app
COPY package.json package-lock.json ./ COPY package.json package-lock.json ./
# onnxruntime-node's postinstall downloads the CUDA build (hundreds of MB) that
# a CPU-only server never loads; the package itself already carries its CPU
# binaries, so skip the download in both install stages.
ENV ONNXRUNTIME_NODE_INSTALL=skip
RUN npm ci RUN npm ci
# ---------------------------------------------------------------------- build # ---------------------------------------------------------------------- build
@@ -13,12 +17,15 @@ COPY tsconfig.json vite.config.ts index.html ./
COPY src ./src COPY src ./src
# Vite copies public/ into dist/, so the served PDF (in-app Guide link) needs it here. # Vite copies public/ into dist/, so the served PDF (in-app Guide link) needs it here.
COPY public ./public COPY public ./public
# The build writes the .br/.gz asset copies the server prefers to send.
COPY scripts ./scripts
RUN npm run build RUN npm run build
# ------------------------------------------------------- production node_modules # ------------------------------------------------------- production node_modules
FROM node:24-bookworm-slim AS prod-deps FROM node:24-bookworm-slim AS prod-deps
WORKDIR /app WORKDIR /app
ENV NODE_ENV=production ENV NODE_ENV=production \
ONNXRUNTIME_NODE_INSTALL=skip
COPY package.json package-lock.json ./ COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force RUN npm ci --omit=dev && npm cache clean --force
+193 -31
View File
@@ -11,8 +11,9 @@ RAW decoding, client galleries, storage quotas and email notifications.
| Mode | How to run | Catalog storage | RAW files | Accounts / galleries | | Mode | How to run | Catalog storage | RAW files | Accounts / galleries |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| Browser only | `npm run dev` | IndexedDB on this device | No — raw needs the server | No | | Browser only | `npm run dev` | IndexedDB on this device | No — raw needs the local engine | No |
| Team server | `npm run server` + `npm run dev` (or `npm start` behind a build) | SQLite + files under `server/data` | Yes — LibRaw demosaic | Yes | | Team server | `npm run server` + `npm run dev` (or `npm start` behind a build) | SQLite + files under `server/data` | Yes — LibRaw demosaic | Yes |
| Desktop app (Windows, Linux, macOS) | the installed bundle — no npm, no account | SQLite in the app's data folder | Yes — bundled LibRaw | One local admin |
Everything edits the same `Edits` JSON document, so a photo edited locally keeps its Everything edits the same `Edits` JSON document, so a photo edited locally keeps its
look when it is later uploaded to a server workspace. look when it is later uploaded to a server workspace.
@@ -38,8 +39,10 @@ look when it is later uploaded to a server workspace.
- [Detail-preserving denoise](#detail-preserving-denoise) - [Detail-preserving denoise](#detail-preserving-denoise)
- [Lens profiles](#lens-profiles) - [Lens profiles](#lens-profiles)
- [Development workflow](#development-workflow) - [Development workflow](#development-workflow)
- [Desktop bundles](#desktop-bundles)
- [Troubleshooting](#troubleshooting) - [Troubleshooting](#troubleshooting)
- [Limitations](#limitations) - [Limitations](#limitations)
- [Changelog](#changelog)
- [Third-party attribution and licences](#third-party-attribution-and-licences) - [Third-party attribution and licences](#third-party-attribution-and-licences)
--- ---
@@ -140,7 +143,7 @@ with a keyword library and reusable metadata presets. Save the current filters a
order as a smart collection. Virtual copies share the master file but keep independent order as a smart collection. Virtual copies share the master file but keep independent
edits; named snapshots preserve alternative looks. edits; named snapshots preserve alternative looks.
**Export and print.** JPEG, PNG, WebP or uncompressed 16-bit TIFF; quality; resize by **Export and print.** JPEG, PNG, WebP, JPEG XL (8-bit, lossy or lossless) or uncompressed 16-bit TIFF; quality; resize by
long edge or percent; filename template (`{name}`, `{date}`, `{time}`, `{index}`); saved long edge or percent; filename template (`{name}`, `{date}`, `{time}`, `{index}`); saved
export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; sRGB, export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; sRGB,
Display P3 or Adobe RGB output with a matching generated ICC profile (JPEG/TIFF); batch Display P3 or Adobe RGB output with a matching generated ICC profile (JPEG/TIFF); batch
@@ -229,9 +232,11 @@ storage, while quotas are stored per account in the database.
| `LUMINARY_INVITE` | *(empty)* | Shared registration code for teammates; personal invite links work without it | | `LUMINARY_INVITE` | *(empty)* | Shared registration code for teammates; personal invite links work without it |
| `LUMINARY_MAX_UPLOAD` | `314572800` (300 MB) | Largest accepted upload, in bytes | | `LUMINARY_MAX_UPLOAD` | `314572800` (300 MB) | Largest accepted upload, in bytes |
| `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable JPEG proxy made from a raw | | `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable JPEG proxy made from a raw |
| `LUMINARY_16BIT` | `1` | Also keep the decoded samples as a 16-bit PNG beside the raw proxy; `0` saves the disk and download it costs, at the price of grading an 8-bit source | | `LUMINARY_16BIT` | `1` | Also keep the decoded samples as a 16-bit PNG beside the raw proxy; `0` saves the disk and download it costs, at the price of grading an 8-bit source. The import dialog can also turn it off for a single import |
| `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB | | `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB |
| `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory | | `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory |
| `LUMINARY_RAW_XTRANS_QUALITY` | `1` | Markesteijn passes for Fujifilm X-Trans files, 1–3. Three passes costs 50 s on a 40 MP frame for detail the 6000 px proxy cannot show |
| `LUMINARY_RAW_TIMEOUT_MS` | `120000` | Ceiling on one demosaic, timed from when a worker starts the job rather than from the request |
| `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) | | `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) |
| `LUMINARY_QUOTA_BYTES` | `107374182400` (100 GiB) | Default per-account storage allowance | | `LUMINARY_QUOTA_BYTES` | `107374182400` (100 GiB) | Default per-account storage allowance |
| `LUMINARY_QUOTA_WARN_RATIO` | `0.9` | Fraction of the quota that triggers warnings, clamped to 0.5–0.99 | | `LUMINARY_QUOTA_WARN_RATIO` | `0.9` | Fraction of the quota that triggers warnings, clamped to 0.5–0.99 |
@@ -277,7 +282,7 @@ directly and have no legacy alias.
```bash ```bash
npm ci npm ci
npm run build # type-checks and bundles dist/ npm run build # type-checks, bundles dist/ and writes .br/.gz copies
npm start # serves dist/ and /api from one Node process npm start # serves dist/ and /api from one Node process
``` ```
@@ -360,6 +365,25 @@ Two independent things to back up:
`GET /api/admin/catalog`, and restore it with `POST /api/admin/catalog`. This does `GET /api/admin/catalog`, and restore it with `POST /api/admin/catalog`. This does
not include image bytes; keep a file-level backup for those. not include image bytes; keep a file-level backup for those.
`npm run backup` automates item 1 without stopping the server: it writes a consistent
`VACUUM INTO` snapshot of the live catalog (WAL included) to `$LUMINARY_DATA/backups`,
re-opens it to run `PRAGMA integrity_check`, records counts in a manifest and prunes to
the last 14 snapshots. `--keep`, `--dir` and `LUMINARY_BACKUP_DIR` change that; originals
are opt-in because they dwarf the catalog:
```bash
npm run backup # catalog only
npm run backup -- --with-originals --keep 30
# nightly at 02:30, keeping the copy off the data volume
30 2 * * * cd /srv/luminary && /usr/bin/npm run backup -- --with-originals --dir /mnt/backups >> /var/log/luminary-backup.log 2>&1
```
To restore, stop the server, copy `catalog-*.db` back as `lumenroom.db` (delete the old
`-wal`/`-shm` files first) and copy `originals-*/` back into the storage root. Previews,
thumbnails, proofs and denoise renders are regenerable; only `originals/` and
`secret.key` must survive.
--- ---
## Docker ## Docker
@@ -423,7 +447,7 @@ Node server (node:http, port 8787)
raw.mjs LibRaw demosaic, embedded-preview fallback raw.mjs LibRaw demosaic, embedded-preview fallback
libraw-*.mjs Node <-> browser shim and decoder worker pool libraw-*.mjs Node <-> browser shim and decoder worker pool
imaging.mjs sharp encode/resize, dependency-free PNG fallback imaging.mjs sharp encode/resize, dependency-free PNG fallback
denoise.mjs job queue and on-disk render cache denoise.mjs denoise queue, base selection and render cache
quota.mjs usage accounting, prune plans, warnings, worker quota.mjs usage accounting, prune plans, warnings, worker
mail.mjs nodemailer transport, admin-editable settings mail.mjs nodemailer transport, admin-editable settings
bridge.mjs dashboard token verification and metadata import bridge.mjs dashboard token verification and metadata import
@@ -434,7 +458,7 @@ Data directory
originals/ uploaded files, byte-for-byte, original extension kept originals/ uploaded files, byte-for-byte, original extension kept
previews/ editable JPEG proxies (raw) and normalised previews previews/ editable JPEG proxies (raw) and normalised previews
thumbs/ grid thumbnails (server-rendered proofs are 560 px) thumbs/ grid thumbnails (server-rendered proofs are 560 px)
denoised/ full-strength denoise renders keyed by pipeline version denoised/ full-strength denoise renders, one per base model
proofs/ rendered proofs for client galleries proofs/ rendered proofs for client galleries
proofThumbs/ thumbnails of those proofs proofThumbs/ thumbnails of those proofs
``` ```
@@ -515,7 +539,7 @@ that predate workspaces are assigned to the oldest account.
| `originals/` | `<photo id>.<original ext>` | Uploaded bytes, untouched; extension preserved | | `originals/` | `<photo id>.<original ext>` | Uploaded bytes, untouched; extension preserved |
| `previews/` | `<photo id>.jpg` or `.png` | Editable proxies; PNG when `sharp` is unavailable | | `previews/` | `<photo id>.jpg` or `.png` | Editable proxies; PNG when `sharp` is unavailable |
| `thumbs/` | `<photo id>.jpg` | Grid thumbnails; server-rendered proof thumbnails are 560 px | | `thumbs/` | `<photo id>.jpg` | Grid thumbnails; server-rendered proof thumbnails are 560 px |
| `denoised/` | `<photo id>.<key>.jpg` | Key encodes the pipeline version; old keys are pruned | | `denoised/` | `<photo id>.<key>.jpg` | Key encodes the pipeline version and the base model; one render is kept per model |
| `proofs/` | `<photo id>.jpg` | Rendered client-gallery proofs | | `proofs/` | `<photo id>.jpg` | Rendered client-gallery proofs |
| `proofThumbs/` | `<photo id>.jpg` | Thumbnails of those proofs | | `proofThumbs/` | `<photo id>.jpg` | Thumbnails of those proofs |
@@ -577,8 +601,8 @@ routes are public and are gated only by the share token.
| GET | `/api/photos/:id/preview` | owner | Stream the editable proxy | | GET | `/api/photos/:id/preview` | owner | Stream the editable proxy |
| GET | `/api/photos/:id/thumb` | owner | Stream the thumbnail (proof thumbnail first, if present) | | GET | `/api/photos/:id/thumb` | owner | Stream the thumbnail (proof thumbnail first, if present) |
| POST | `/api/photos/:id/proof` | owner | Store a rendered JPEG proof and its thumbnail from base64 | | POST | `/api/photos/:id/proof` | owner | Store a rendered JPEG proof and its thumbnail from base64 |
| POST | `/api/photos/:id/denoise` | owner | Queue a full-strength denoise render; returns a job id | | POST | `/api/photos/:id/denoise` | owner | Queue a full-strength render; body `{"base": "guided" \| "scunet" \| "nlm"}`, default `guided`; returns a job id |
| GET | `/api/denoise/jobs/:id` | session | Job state: running/done/error, timing, stats, cache hit | | GET | `/api/denoise/jobs/:id` | session | Job state: running/done/error, `progress` (`stage`, `done`, `total` tiles), `ms`, `bytes`, `stats` and `cached` for a cache hit |
| GET | `/api/photos/:id/denoised?v=<key>` | owner | Stream the cached denoise render | | GET | `/api/photos/:id/denoised?v=<key>` | owner | Stream the cached denoise render |
| DELETE | `/api/photos/:id/denoised` | owner | Drop all denoise renders for the photo | | DELETE | `/api/photos/:id/denoised` | owner | Drop all denoise renders for the photo |
| GET | `/api/quota` | session | The caller's quota state | | GET | `/api/quota` | session | The caller's quota state |
@@ -857,7 +881,10 @@ The browser cannot demosaic camera raw, so the server does it during upload:
texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per
channel instead of 256. A photo without a sidecar — one imported before this existed, channel instead of 256. A photo without a sidecar — one imported before this existed,
a non-raw file, or a build with `LUMINARY_16BIT=0` — simply grades the JPEG, so a non-raw file, or a build with `LUMINARY_16BIT=0` — simply grades the JPEG, so
nothing breaks either way. The grid and Compare read the same samples: on first nothing breaks either way. The import dialog offers this as **Import raws at 16-bit**,
checked by default; unchecking it for an import asks the server for the 8-bit path
(`?sidecar=0` on the upload), which decodes the same but skips the second encode and
its disk cost. The grid and Compare read the same samples: on first
request the server writes a camera-native tile the size of the JPEG thumbnail at request the server writes a camera-native tile the size of the JPEG thumbnail at
`previews/<id>.t16.png`, and Compare loads the full sidecar, so a loaded DCP profile `previews/<id>.t16.png`, and Compare loads the full sidecar, so a loaded DCP profile
shows in every view of the photo. Preset previews do the same. shows in every view of the photo. Preset previews do the same.
@@ -883,8 +910,11 @@ same matrix from a DCP `ColorMatrix1` — `inverse(rowNormalise(ColorMatrix · x
— matches LibRaw's `rgb_cam` to 2.2e-5 on a D700 NEF and 2.7e-5 on a 5D Mark II CR2. — matches LibRaw's `rgb_cam` to 2.2e-5 on a D700 NEF and 2.7e-5 on a 5D Mark II CR2.
**Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default **Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default
`min(4, cores−1)`, `LUMINARY_RAW_WORKERS`), and the browser uploads several files at a `min(4, cores−1)`, `LUMINARY_RAW_WORKERS`). The browser keeps four raws in flight to
time. Each instance owns one worker thread; extra jobs queue. Idle instances are match that pool and queues the rest, so the server is never asked for more frames than it
can decode; camera JPEGs also go four at a time, since the browser decodes those itself.
Eight 12 MP NEFs took 20.8 s two at a time and 17.4 s four at a time (8 was 15.8 s, not
worth the extra memory). Each instance owns one worker thread; extra jobs queue. Idle instances are
disposed after `LUMINARY_RAW_IDLE_MS` and recreated on demand, so a burst of imports disposed after `LUMINARY_RAW_IDLE_MS` and recreated on demand, so a burst of imports
does not pin memory forever. A decoder that reports a dead worker is recycled rather does not pin memory forever. A decoder that reports a dead worker is recycled rather
than returned to the pool. Measured on this repo with 8 mixed raws (20 MP average): than returned to the pool. Measured on this repo with 8 mixed raws (20 MP average):
@@ -895,6 +925,17 @@ than returned to the pool. Measured on this repo with 8 mixed raws (20 MP averag
| 4 | 5.2 s | 3.7× | ~2.5 GB | | 4 | 5.2 s | 3.7× | ~2.5 GB |
| 8 | 3.5 s | 5.4× | ~3.5 GB | | 8 | 3.5 s | 5.4× | ~3.5 GB |
Those are Bayer files. Fujifilm X-Trans frames behave differently in this wasm build: four
concurrent 40 MP X-Trans decodes each took ~65 s here against ~9 s on their own, so the
worker pool buys throughput in principle but not latency for that sensor. Two things
mattered more than the pool. LibRaw's default 3-pass Markesteijn demosaic took **49.9 s** on
one X-T5 frame; one pass takes **8.8 s** and is what `LUMINARY_RAW_XTRANS_QUALITY` selects.
And the 45 s decode timeout used to count time spent queued for a worker, so a parallel Fuji
import timed out in waves — every file in a wave fell back to the camera preview, and the
byte-scan fallback could hand back a truncated JPEG, which surfaced as a 0x0 photo. The
timeout now starts when a worker picks the job up, an abandoned worker is recycled instead
of being returned to the pool, and the fallback only stores bytes that actually decode.
Raise the worker count on a big machine; keep it low on a small VPS, where each worker Raise the worker count on a big machine; keep it low on a small VPS, where each worker
can hold a few hundred MB while decoding. `GET /api/health` reports the pool size and can hold a few hundred MB while decoding. `GET /api/health` reports the pool size and
busy count. busy count.
@@ -903,30 +944,83 @@ busy count.
## Detail-preserving denoise ## Detail-preserving denoise
`server/denoise/` is a dependency-free pipeline (planes, noise estimation, colour, `server/denoise/` is Luminary's denoise pipeline: planes, noise estimation, colour,
detail, RGB reconstruction) adapted from the `raw-noise` project. It reconstructs each detail and RGB reconstruction, adapted from the `raw-noise` project, driving one of three
pixel as a crossfade between the source and a denoised base, so the result is bounded by base denoisers. The result is a per-pixel crossfade between the source and the denoised
the original pixels and cannot ring or overshoot: flat noise is replaced, structure is base, so it is bounded by the original pixels and cannot ring or overshoot: flat noise is
handed back verbatim. replaced, structure is handed back verbatim.
**Provenance.** `raw-noise` is not published on npm, and no copyright or licence notice The **AI denoise** panel offers the three bases in this order:
for it is included in this repository. Before redistributing Luminary, add the origin's
notice and terms to `server/denoise/`, or replace that folder with an independently | Base | Implementation | One 256 × 256 test frame |
licensed implementation. | --- | --- | --- |
| **Guided** (default) | Guided filter in the copied pipeline; fastest, keeps the most fine texture | 0.06 s |
| **SCUNet** | Learned colour denoiser `server/denoise/scunet_color_25.onnx`, run through `onnxruntime-node` on 256 px tiles with a 32 px overlap | 12.1 s (4 tiles) |
| **NLM** | Non-local means in the copied pipeline; slower than Guided, smooths less than SCUNet | 0.43 s |
Timings are what the three bases measured here on a 256² noisy frame; a full frame costs
more in proportion to its area (and SCUNet to its tile count). The base is stored per
photo in `aiDenoise.model` and is part of the render key, so switching models does not
invalidate another model's render. SCUNet is the only path that needs
`onnxruntime-node`; it is imported lazily, so Guided and NLM keep working when the native
binding cannot load. The package is pinned to `1.23.0`, the last release that ships both
macOS architectures, and its install step is skipped in the Dockerfile and the desktop
builds (`ONNXRUNTIME_NODE_INSTALL=skip`) because only the CPU binaries in the package are
used.
**Provenance and licences.** `raw-noise` is not published on npm, and no copyright or
licence notice for it is included in this repository. Before redistributing Luminary, add
the origin's notice and terms to `server/denoise/`, or replace that folder with an
independently licensed implementation. The SCUNet weights are Apache-2.0 (upstream
`cszn/SCUNet`, ONNX export by `Heliosoph/scunet-onnx`) and ONNX Runtime is MIT; both are
listed in [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).
- The server always renders the full-strength denoise and the GPU blends it, so the - The server always renders the full-strength denoise and the GPU blends it, so the
Amount slider is instant, one file serves every amount, and the amount cannot be Amount slider is instant, one file serves every amount, and the amount cannot be
applied twice. applied twice.
- Renders are cached in `denoised/` under a key that includes `PIPELINE_VERSION`. Bump - Renders are cached in `denoised/` as `<photo id>.<key>.jpg`, where the key is the first
that constant whenever the copied pipeline changes output, or stale renders will be 12 hex characters of `sha1(photoId|PIPELINE_VERSION|base)`. One render is kept per
served as current. model, so switching back to a model is instant; a finished run prunes only keys from an
older pipeline version. Bump `PIPELINE_VERSION` in `server/denoise.mjs` whenever the
copied pipeline or the SCUNet tiling changes output, or stale renders will be served as
current.
- Each run is seconds of CPU, so jobs go through a capped queue - Each run is seconds of CPU, so jobs go through a capped queue
(`LUMINARY_DENOISE_WORKERS`, default `min(4, cores−1)`). A second request for the same (`LUMINARY_DENOISE_WORKERS`, default `min(4, cores−1)`). A second request for the same
photo joins the run already in progress instead of starting an identical one. photo and base joins the run already in progress instead of starting an identical one,
and a request whose render already exists returns at once with `cached: true`.
- While a job runs it reports `progress` (`stage` and, for SCUNet, the tile count), which
the panel turns into a real status line instead of a spinner.
- The job table keeps the newest 40 entries and never drops a queued or running job. - The job table keeps the newest 40 entries and never drops a queued or running job.
--- ---
## Metadata portability
The catalog is not the only copy of what you typed. Ratings, colour labels, keywords and
IPTC fields are written into XMP in both directions, so a library can leave.
- **Two keyword lists, on purpose.** `photo.keywords` holds the leaf terms and is what search
and filters read; `photo.keywordPaths` holds the full `A > B > C` chains. Typing
`Nature > Birds > Robin` records `Nature`, `Nature > Birds` and the full path, and adds
`Robin` to the flat list, so taggers never have to think about the tree and search never
has to.
- **The pair Lightroom writes.** `dc:subject` carries the leaves, `lr:hierarchicalSubject`
the paths, and `xmp:Rating` / `xmp:Label` the rating and colour label. Another editor
sees the same thing Luminary does; a library can be rebuilt from sidecars instead of
from this database.
- **IPTC core.** Headline, credit, source, city, state, country and sublocation are edited
in the Metadata panel and written as `photoshop:` and `Iptc4xmpCore:` properties.
- **Import reads both halves.** Importing a sidecar applies its develop settings and its
cataloguing fields independently: a metadata-only file from a DAM imports without a
`crs:` grade, and a grade imports without keywords. Nothing the file omits is cleared.
- **Exported files carry it too.** A JPEG export embeds the same packet as the sidecar, so a
delivered file keeps its rating, keywords, hierarchy and IPTC.
`src/lib/keywords.ts` owns the path rules (separators, ancestors, pruning a subtree and
leaving no orphan leaves); `src/lib/xmp.ts` owns the mapping to and from XMP.
---
## Lens profiles ## Lens profiles
Lens correction uses the calibration data of the Lens correction uses the calibration data of the
@@ -971,15 +1065,31 @@ positions. Camera-lens defaults require both a normalised camera and lens name t
| `npm run server:dev` | Server with `node --watch` | | `npm run server:dev` | Server with `node --watch` |
| `npm run dev` | Vite HMR on 5173 | | `npm run dev` | Vite HMR on 5173 |
| `npm run typecheck` | `tsc --noEmit` | | `npm run typecheck` | `tsc --noEmit` |
| `npm test` | Vitest, one pass then exit | | `npm test` | Vitest, one pass then exit: pure logic plus the server HTTP suite |
| `npm run backup` | Snapshot the catalog (originals optional) without stopping the server |
| `npm run precompress` | Write the `.br`/`.gz` asset copies by hand; `npm run build` does this |
| `npm run check:render` | Headless Chrome check that the 16-bit sidecar and JPEG proxy upload in the same row order | | `npm run check:render` | Headless Chrome check that the 16-bit sidecar and JPEG proxy upload in the same row order |
| `npm run predeploy` | Typecheck, unit suite, render check, then build — run this before pushing a deploy; the build is skipped when only test files changed since the last build | | `npm run predeploy` | Typecheck, unit suite, render check, then build — run this before pushing a deploy; the build is skipped when only test files changed since the last build |
| `npm run deploy` | Predeploy gate, then rsync, remote build, restart and bundle-hash check (see [Production deployment](#production-deployment)) | | `npm run deploy` | Predeploy gate, then rsync, remote build, restart and bundle-hash check (see [Production deployment](#production-deployment)) |
`npm install` also installs `onnxruntime-node` for the SCUNet denoise base. Its install
step downloads the CUDA build (~350 MB) unless `ONNXRUNTIME_NODE_INSTALL=skip` is set
before the install; the Dockerfile and the desktop builds set it, because only the CPU
binaries that ship inside the package are used.
### Continuous integration
`.gitea/workflows/ci.yml` runs on every push and pull request: `npm ci`,
`npm run typecheck`, `npm test` and `npm run build` inside a `node:24-bookworm`
container, then `node --check` on every `server/*.mjs`. It only needs Docker on the
runner, so the same gate works on the LAN Gitea instance. Release binaries are still
built and attached by hand; the workflow is what keeps `main` buildable.
Conventions worth knowing before changing code: Conventions worth knowing before changing code:
- The server is plain ESM (`.mjs`) with no build step. Keep it framework-free and avoid - The server is plain ESM (`.mjs`) with no build step. Keep it framework-free; native
native modules; `node:sqlite` is deliberate, and `sharp` must stay optional. modules stay optional — `node:sqlite` is deliberate, `sharp` must stay optional, and
`onnxruntime-node` is loaded lazily and only for SCUNet.
- The client is strict TypeScript with `noEmit`; Vite builds only `src/` and `public/`. - The client is strict TypeScript with `noEmit`; Vite builds only `src/` and `public/`.
- Edits are data, not pixels: adding a control means extending `src/types.ts`, the - Edits are data, not pixels: adding a control means extending `src/types.ts`, the
renderer uniforms/shaders, `normalizeEdits()` defaults, the export path and the panel renderer uniforms/shaders, `normalizeEdits()` defaults, the export path and the panel
@@ -1007,8 +1117,13 @@ Conventions worth knowing before changing code:
| `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values | | `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values |
| `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, rendering-intent selection and CMYK profiles | | `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, rendering-intent selection and CMYK profiles |
| `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching | | `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching |
| `server/http.test.mjs` | Real server on a throwaway data directory: signup/invite rules, cross-owner isolation, upload quota accounting, byte ranges, unreadable files not killing the process, gallery download cap |
There are no server integration tests; the API is exercised through the UI. `server/http.test.mjs` spawns `server/index.mjs` on a random loopback port with a
temporary `LUMINARY_DATA`, drives it with `fetch` and deletes the directory afterwards,
so it needs no fixtures and never touches a real catalog. Its permission test (an
unreadable original must answer 404 instead of crashing the process) is skipped when the
suite runs as root, because root ignores file modes.
`npm run check:render` covers the one thing the unit suite cannot: what a shader does to `npm run check:render` covers the one thing the unit suite cannot: what a shader does to
real GPU pixels. It encodes a 16-bit sidecar with the server's own encoder, serves it real GPU pixels. It encodes a 16-bit sidecar with the server's own encoder, serves it
@@ -1024,14 +1139,51 @@ when none is installed.
--- ---
## Desktop bundles
The app also ships as a double-clickable desktop bundle for people who do not want a
terminal. The current release is **0.5.4**: Windows and Linux bundles are built; the
macOS app stays at 0.5.1 until it can be built on a Mac.
- **Windows** — per-user setup exe or portable zip from `windows/releases/`. The app
opens in its own native window (`LuminaryWindow.exe`, WebView2), so no browser, Edge
profile or Microsoft account is involved. `Luminary.exe` is the launcher; `-Browser`
opens a normal tab instead, and `-Stop` stops the local engine.
- **Linux** — `.deb` or portable tarball from `linux/releases/`; the launcher picks a
Chromium-based browser for its app window or falls back to a normal tab.
- **macOS** — `macos/build.mjs`, run on a Mac, produces the `.app`, zip and dmg.
Each bundle starts a Node process from its own folder that serves the UI and decodes
raws on `127.0.0.1` only. That process is the *local engine*: it is a background
service on the same PC, needs no network, and never uploads anything. The launcher
waits for it with a direct loopback connection and opens the app window with proxies
disabled, so a disconnected machine still starts and imports.
Build them from the repository root (artifacts land outside the checkout and, with
`--publish`, are copied into the release folders):
```bash
node windows/build.mjs --skip-build --installer --publish \
--webview2 /path/to/LuminaryWindow.exe
node linux/build.mjs --skip-build --publish
```
`windows/README.md`, `linux/README.md` and `macos/README.md` cover the packaging
details, the isolation guarantees and the smoke tests (`windows/SMOKE-WINDOWS.ps1`,
`linux/SMOKE-LINUX.sh`).
---
## Troubleshooting ## Troubleshooting
| Symptom | Cause and fix | | Symptom | Cause and fix |
| --- | --- | | --- | --- |
| "Cannot reach the Luminary server" in the app | The Vite dev proxy targets `127.0.0.1:8787`. Start `npm run server`, and do not change `PORT` while using `npm run dev` | | "Cannot reach the Luminary local engine" in the desktop app | The bundled engine stopped, or the window's request to `127.0.0.1` was routed through a system proxy. Start the app again; 0.5.4 probes and opens the window with proxies disabled |
| "Cannot reach the Luminary server" in a dev build | The Vite dev proxy targets `127.0.0.1:8787`. Start `npm run server`, and do not change `PORT` while using `npm run dev` |
| `503` "The web build is missing" | `npm start` was run without `dist/`. Run `npm run build` first, or use `npm run dev` | | `503` "The web build is missing" | `npm start` was run without `dist/`. Run `npm run build` first, or use `npm run dev` |
| Raw upload returns `422` | LibRaw could not decode the file and no embedded preview was found. Check `GET /api/health` → `raw.libraw`; install dependencies and confirm the camera is supported | | Raw upload returns `422` | LibRaw could not decode the file and no embedded preview was found. Check `GET /api/health` → `raw.libraw`; install dependencies and confirm the camera is supported |
| Import is slow or the machine swaps | Lower `LUMINARY_RAW_WORKERS`; each decoder holds a worker and a few hundred MB | | Import is slow or the machine swaps | Lower `LUMINARY_RAW_WORKERS`; each decoder holds a worker and a few hundred MB |
| Fuji imports are slow or a Fuji file fails to import | X-Trans demosaic is the cost, not the network. `LUMINARY_RAW_XTRANS_QUALITY` defaults to 1 pass (~9 s for 40 MP); 3 is sharper and about five times slower. A file that still fails should now import from the camera preview — check its `decode` field for `embedded` |
| Emails never arrive | Gmail needs 2-Step Verification and an app password, not the account password. Use **Send test email**; admin-saved settings override the environment | | Emails never arrive | Gmail needs 2-Step Verification and an app password, not the account password. Use **Send test email**; admin-saved settings override the environment |
| Quota looks wrong after deleting | Trash still counts toward usage. Empty Trash to release the bytes | | Quota looks wrong after deleting | Trash still counts toward usage. Empty Trash to release the bytes |
| Cookies not marked `Secure` behind HTTPS | The proxy must forward `X-Forwarded-Proto: https` | | Cookies not marked `Secure` behind HTTPS | The proxy must forward `X-Forwarded-Proto: https` |
@@ -1041,6 +1193,14 @@ when none is installed.
--- ---
## Changelog
Release notes live in [CHANGELOG.md](CHANGELOG.md): 0.5.4 is the desktop and offline
release (before/after split, native Windows window, local-engine wording, offline
start), 0.5.2 added the three denoise models, and 0.5.1 introduced the Ubuntu package.
---
## Limitations ## Limitations
- **Not a cloud service.** No hosted deployment and no camera driver: tethering is a - **Not a cloud service.** No hosted deployment and no camera driver: tethering is a
@@ -1179,7 +1339,9 @@ full CC BY-SA 3.0 text. Before distributing Luminary or its container image:
(OFL-1.1) and DejaVu Sans Mono (Bitstream Vera licence) — with any redistributed (OFL-1.1) and DejaVu Sans Mono (Bitstream Vera licence) — with any redistributed
copy. copy.
7. Record the terms of the `server/denoise/` pipeline's `raw-noise` origin; it is not 7. Record the terms of the `server/denoise/` pipeline's `raw-noise` origin; it is not
published on npm and its licence is currently undocumented here. published on npm and its licence is currently undocumented here. The SCUNet weights
and ONNX Runtime are already catalogued in `THIRD_PARTY_NOTICES.md`; ship that file
and the model's `.onnx.data` shard with the app.
### No endorsement ### No endorsement
+136
View File
@@ -0,0 +1,136 @@
# Security audit
Date: 1 December 2026 · Version: 0.5.4 · Scope: this repository (server, client,
build/release scripts, dependencies). Review was static: dependency scan plus a
targeted read of the server's trust boundaries. No infrastructure, host or
third-party service was tested.
## Summary
No critical or high-severity issue was found in code that ships and runs by
default. The production dependency tree has two `high` advisories that come from
one transitive package (`adm-zip` inside `onnxruntime-node`) and are not
reachable through anything this application does.
Everything else is either a development-only toolchain advisory, a hardening
opportunity, or an operational note.
| Area | Result |
| --- | --- |
| Production dependencies | 0 critical, 0 moderate, 2 high (one transitive package, not reachable) |
| Development dependencies | 2 critical, 3 high, 3 moderate — dev server and test runner only |
| Authentication and sessions | scrypt with per-user salt, random tokens, HttpOnly/SameSite cookies, rate limiting |
| Authorisation | Every `/api/admin/*` route calls `requireAdmin`; gallery routes are token-scoped |
| Injection | No `eval`, no `new Function`, no `innerHTML`/`dangerouslySetInnerHTML`; SQLite access is entirely prepared statements |
| Path traversal | Static and tether paths are resolved and compared against a root; uploads use generated IDs |
| Secret handling | SMTP and bridge credentials AES-256-GCM encrypted at rest; no secrets in the tree |
| Uploads | Global size cap, content-length checked before reading, quota per account |
| Outbound requests | Immich and dashboard URLs are operator-configured, not user-configured |
## Dependency findings
### 1. `adm-zip` — high, transitive (`onnxruntime-node` → `adm-zip`)
Advisories: crafted ZIP triggers a 4 GB allocation; extraction follows
destination symlinks and can overwrite arbitrary files; uncontrolled memory
allocation via a declared size.
Reachability here: `onnxruntime-node` declares `adm-zip` for its own archive
handling. Luminary never extracts a ZIP it did not create: the denoise models are
read from local storage, and the only ZIP code in the app writes archives
(`src/lib/zip.ts`) rather than reading them. No route accepts a ZIP. Impact is
therefore latent rather than exploitable.
Fix: upgrade `onnxruntime-node` 1.23.0 → 1.31.1 (`npm i onnxruntime-node@1.31.1`).
That is the version npm proposes, a non-major bump. Not applied in this pass
because it changes the denoise runtime and needs its own regression run.
### 2. Development toolchain — 2 critical, 3 high, 3 moderate
`vitest`/`tinypool`/`@vitest/mocker` (prototype-pollution gadget to RCE, arbitrary
file read via the Vitest UI server), `vite` (path traversal in optimised-deps
`.map` handling, `launch-editor` NTLM hash disclosure), `esbuild` (dev server
request proxying).
None of these ship: the release bundle is static `dist/` output and the Node
server does not run Vite. They matter only for a machine that runs `npm run dev`
or the Vitest UI while exposed to an untrusted network. Fix by moving to the
current Vite/Vitest majors on a branch, not by a patch bump inside the current
majors.
`npm audit --omit=dev` is the meaningful gate for releases; add it to
`predeploy` if that gate should be enforced.
## Verified controls
- **Password storage**: `scrypt` (`server/auth.mjs`), 32-byte key, per-hash random
salt, compared with `timingSafeEqual`. Non-existent accounts spend the same
scrypt work and return the same message, so the endpoint does not reveal which
addresses are registered.
- **Sessions**: 32-byte random tokens, `HttpOnly`, `SameSite=Lax`, `Secure` when
the request arrived over HTTPS, 30-day lifetime, server-side revocation on logout.
- **Rate limiting**: sign-in is limited per IP and per IP+account (429 with
`Retry-After`), gallery unlock is limited per link.
- **Authorisation**: 26 `requireAdmin` checks cover the admin surface; missing or
disabled accounts are rejected; the desktop local owner is only used when
`LUMINARY_LOCAL=1`.
- **Gallery links**: separate password hash with its own salt, constant-time
compare, unlock cookie random per session and held in memory, so a restart
re-locks the gallery. Share tokens are 18 random bytes.
- **Bridge**: HMAC-SHA256 over the payload, version-tagged, expiry checked,
constant-time signature compare.
- **Path handling**: static requests are resolved then checked with
`path.relative` against `dist`; tether file names go through `basename` and
must match exactly; stored files are addressed by generated IDs.
- **Uploads**: `MAX_UPLOAD` enforced against `content-length` before reading and
again while streaming.
- **Headers**: CSP with `object-src 'none'`, `frame-ancestors 'self'`,
`nosniff`, `SAMEORIGIN`, `same-origin` referrer policy, restrictive
`Permissions-Policy`. No CORS headers are emitted, so browsers cannot read
responses cross-origin.
- **Secrets**: SMTP app password and bridge tokens are sealed with AES-256-GCM
(`server/secrets.mjs`); the key comes from `LUMINARY_SECRET_KEY` or a
`0600` file beside the database. No credentials or API keys are committed.
## Hardening opportunities (not vulnerabilities)
1. **CSP includes `'unsafe-eval'`.** It is there for the WebAssembly engines. The
modern token is `'wasm-unsafe-eval'`; keeping the broader one means any future
DOM-XSS can compile and run script. Tighten to `'wasm-unsafe-eval'` and test
LibRaw/JXL/ONNX still initialise.
2. **Server-side request forgery surface.** The Immich base URL and dashboard URL
are operator-supplied and fetched by the server with credentials attached.
An admin can point them at internal services. Acceptable for a self-hosted
tool, but worth blocking loopback/link-local targets by default, or stating
the trust assumption in the docs.
3. **Per-account sign-in limiting is scoped by IP.** A distributed attempt against
one address is not globally throttled; scrypt cost is the only brake. A global
per-account counter would close that.
4. **30-day sessions** with no rotation on privilege change. Revoking sessions on
password change is worth adding.
5. **No HSTS, no built-in TLS.** Correct for a loopback desktop app; for team
installs it depends on a reverse proxy, so document that.
6. **`secret.key` beside the database** protects backups and dumps, not a full
data-directory compromise. `LUMINARY_SECRET_KEY` is the stronger option and
should be recommended for team installs.
7. **Minimum password length is 8** with no breach-list check. Fine; consider 12
for admin accounts.
## Release artefact checks
- The desktop bundles copy `dist/` and production `node_modules/`; no dev
dependencies or test files are included.
- The new JPEG XL encoder is WebAssembly executed in the browser sandbox, loads
only when a JXL export is chosen, makes no network requests, and is Apache-2.0
(`@jsquash/jxl`, libjxl BSD-3-Clause). No new server-side attack surface.
- JPEG exports re-encode pixels, so camera EXIF is not carried into delivered
files; only the XMP block Luminary writes is added.
## Recommended order
1. `onnxruntime-node@1.31.1` with a denoise regression run (clears both production
highs).
2. Tighten CSP to `'wasm-unsafe-eval'` and re-test raw, JXL and denoise loading.
3. Vite/Vitest major upgrade on a branch (clears every dev advisory).
4. Seal the Immich API key if it is not already sealed.
5. Add `npm audit --omit=dev --audit-level=high` to `scripts/predeploy.mjs`.
+14 -5
View File
@@ -24,8 +24,17 @@ Versions are those resolved in `package-lock.json`; the lens database pin is
| libvips (bundled in `sharp` binaries) | shipped by `sharp` 0.35.5 | LGPL-2.1-or-later | © libvips contributors — https://github.com/libvips/libvips | | libvips (bundled in `sharp` binaries) | shipped by `sharp` 0.35.5 | LGPL-2.1-or-later | © libvips contributors — https://github.com/libvips/libvips |
| `exifr` | 7.1.3 | MIT | © 2020 Mike Kovařík, Mutiny.cz — https://github.com/MikeKovarik/exifr | | `exifr` | 7.1.3 | MIT | © 2020 Mike Kovařík, Mutiny.cz — https://github.com/MikeKovarik/exifr |
| `nodemailer` | 7.0.13 | MIT-0 | © 2011-2023 Andris Reinman — https://github.com/nodemailer/nodemailer | | `nodemailer` | 7.0.13 | MIT-0 | © 2011-2023 Andris Reinman — https://github.com/nodemailer/nodemailer |
| `onnxruntime-node` (ONNX Runtime native libraries) | 1.23.0 | MIT | © Microsoft Corporation — https://github.com/microsoft/onnxruntime |
| SCUNet colour-denoise weights (`server/denoise/scunet_color_25.onnx`) | `scunet_color_25` | Apache-2.0 | © Kai Zhang and SCUNet contributors — https://github.com/cszn/SCUNet; ONNX export https://github.com/Heliosoph/scunet-onnx |
| React / React DOM | 18.3.1 | MIT | © Facebook, Inc. and its affiliates — https://github.com/facebook/react | | React / React DOM | 18.3.1 | MIT | © Facebook, Inc. and its affiliates — https://github.com/facebook/react |
`onnxruntime-node` is pulled in only by the optional SCUNet denoise base; the Guided and
NLM bases are plain TypeScript. Its install step is skipped in the Docker image and the
desktop bundles (`ONNXRUNTIME_NODE_INSTALL=skip`), so only the CPU runtime that ships in
the package is distributed. The SCUNet model is a converted export of the upstream
Apache-2.0 weights and keeps that licence; its `.onnx` file and the external `.onnx.data`
shard are one artefact and must travel together.
The lens database is a separate asset from Luminary's code: CC BY-SA 3.0 applies to The lens database is a separate asset from Luminary's code: CC BY-SA 3.0 applies to
Lensfun's calibration data, not to the correction engine that reads it. Attribution and Lensfun's calibration data, not to the correction engine that reads it. Attribution and
share-alike requirements are summarised in the README under share-alike requirements are summarised in the README under
@@ -138,9 +147,9 @@ the following restrictions:
### Apache-2.0 ### Apache-2.0
Applies to `sharp` and TypeScript. The full text is included verbatim in Applies to `sharp`, TypeScript and the SCUNet denoise weights. The full text is included
[`licenses/Apache-2.0.txt`](licenses/Apache-2.0.txt), copied from the licence that verbatim in [`licenses/Apache-2.0.txt`](licenses/Apache-2.0.txt), copied from the licence
`sharp` ships. that `sharp` ships.
### ISC ### ISC
@@ -172,6 +181,6 @@ and libvips notices with it.
## Trademarks ## Trademarks
Lensfun, LibRaw, libvips, sharp, React, Node.js, Debian, Liberation and DejaVu are the Lensfun, LibRaw, libvips, sharp, ONNX Runtime, SCUNet, Microsoft, React, Node.js,
marks of their respective owners. They are used only to identify the software Debian, Liberation and DejaVu are the marks of their respective owners. They are used only to identify the software
involved; Luminary is not affiliated with or endorsed by any of them. involved; Luminary is not affiliated with or endorsed by any of them.
Binary file not shown.
+34 -30
View File
@@ -198,9 +198,9 @@
<p>Every figure is a real screenshot from a running installation with a portrait session loaded. The file names, cameras and metadata are the uploaded originals; the cull, crop and grade shown were arranged for the guide. Keys are written for both platforms: <kbd>⌘</kbd> means Command on macOS, <kbd>Ctrl</kbd> on Windows and Linux. Boxes marked <b>Try this</b> are short exercises that use the kind of photo you probably have on disk.</p> <p>Every figure is a real screenshot from a running installation with a portrait session loaded. The file names, cameras and metadata are the uploaded originals; the cull, crop and grade shown were arranged for the guide. Keys are written for both platforms: <kbd>⌘</kbd> means Command on macOS, <kbd>Ctrl</kbd> on Windows and Linux. Boxes marked <b>Try this</b> are short exercises that use the kind of photo you probably have on disk.</p>
<div class="glance"> <div class="glance">
<div><strong>Local first</strong><span>The browser keeps its own catalogue in IndexedDB. A server adds shared storage and raw decoding; it is not required for JPEG/PNG work.</span></div> <div><strong>Local first</strong><span>The browser keeps its own catalogue in IndexedDB. A team server adds shared storage and accounts; raw decoding runs in the engine bundled with the desktop app, so it is not required for JPEG/PNG work.</span></div>
<div><strong>Non-destructive</strong><span>Edits are parameters beside the file. The original pixels are only ever read, never rewritten.</span></div> <div><strong>Non-destructive</strong><span>Edits are parameters beside the file. The original pixels are only ever read, never rewritten.</span></div>
<div><strong>Raw aware</strong><span>Camera raws are demosaiced by the bundled LibRaw server, then developed like any other frame — with a 16-bit sidecar for grading.</span></div> <div><strong>Raw aware</strong><span>Camera raws are demosaiced by the bundled LibRaw engine on this PC, then developed like any other frame — with a 16-bit sidecar for grading.</span></div>
</div> </div>
</div> </div>
@@ -224,7 +224,7 @@
<ul> <ul>
<li>Drag a card or folder onto the window.</li> <li>Drag a card or folder onto the window.</li>
<li>Pick the event, or type a new name.</li> <li>Pick the event, or type a new name.</li>
<li>Raws and TIFF need the server; JPEG/PNG do not.</li> <li>Raws and TIFF need the local engine (bundled with the desktop app); JPEG/PNG do not.</li>
</ul> </ul>
</div> </div>
<div class="qs-box"> <div class="qs-box">
@@ -255,7 +255,7 @@
<div class="qs-box"> <div class="qs-box">
<h2>6 · Deliver</h2> <h2>6 · Deliver</h2>
<ul> <ul>
<li><b>Export</b> → JPEG/PNG/WebP/TIFF, size, recipe, watermark.</li> <li><b>Export</b> → JPEG/PNG/WebP/JPEG XL/TIFF, size, recipe, watermark.</li>
<li><b>Share</b> → client gallery link with picks and comments.</li> <li><b>Share</b> → client gallery link with picks and comments.</li>
<li><b>Print</b> → A4/Letter/5×7 through the same renderer.</li> <li><b>Print</b> → A4/Letter/5×7 through the same renderer.</li>
</ul> </ul>
@@ -280,7 +280,7 @@
</div> </div>
</div> </div>
<div class="qs-foot">If a raw will not import, the server is offline or the camera is unsupported by LibRaw — see Chapter 4. If the canvas is black, WebGL 2 is unavailable — see Chapter 21.</div> <div class="qs-foot">If a raw will not import, the local engine is not running or the camera is unsupported by LibRaw — see Chapter 4. If the canvas is black, WebGL 2 is unavailable — see Chapter 21.</div>
</section> </section>
<!-- ============================== 1 ============================== --> <!-- ============================== 1 ============================== -->
@@ -306,7 +306,7 @@
<tbody> <tbody>
<tr><td>Browser</td><td>A current Chromium (Chrome, Edge), Firefox or Safari with WebGL 2. Hardware acceleration is strongly recommended: previews, thumbnails and exports all render on the GPU.</td></tr> <tr><td>Browser</td><td>A current Chromium (Chrome, Edge), Firefox or Safari with WebGL 2. Hardware acceleration is strongly recommended: previews, thumbnails and exports all render on the GPU.</td></tr>
<tr><td>Display</td><td>1280 × 800 minimum. The layout is built for a laptop and expands to fill a desktop screen.</td></tr> <tr><td>Display</td><td>1280 × 800 minimum. The layout is built for a laptop and expands to fill a desktop screen.</td></tr>
<tr><td>Server (optional)</td><td>Node 22.5+ or Docker, for raw and TIFF decoding, shared storage, accounts and proofing links. JPEG, PNG, WebP and AVIF work without it.</td></tr> <tr><td>Team server (optional)</td><td>Node 22.5+ or Docker, for shared storage, accounts and proofing links. The desktop app bundles the same engine for raw and TIFF decoding; JPEG, PNG, WebP and AVIF work without either.</td></tr>
<tr><td>Windows app (optional)</td><td>Windows 10 or 11, 64-bit. Nothing else: Node, .NET and the VC++ runtime are bundled or not needed.</td></tr> <tr><td>Windows app (optional)</td><td>Windows 10 or 11, 64-bit. Nothing else: Node, .NET and the VC++ runtime are bundled or not needed.</td></tr>
</tbody> </tbody>
</table> </table>
@@ -330,7 +330,7 @@
<section class="chapter"> <section class="chapter">
<div class="kicker">Chapter 2</div> <div class="kicker">Chapter 2</div>
<h1>Installing Luminary</h1> <h1>Installing Luminary</h1>
<p class="lede">Three supported ways in. Pick the one that matches how the machine will be used; they all run the same server and the same interface.</p> <p class="lede">Three supported ways in. Pick the one that matches how the machine will be used; they all run the same engine and the same interface. The Linux and macOS bundles install the same desktop app.</p>
<h2>Option A — Docker (recommended for a server)</h2> <h2>Option A — Docker (recommended for a server)</h2>
<ol class="steps"> <ol class="steps">
@@ -372,18 +372,18 @@
<section class="chapter"> <section class="chapter">
<div class="kicker">Chapter 3</div> <div class="kicker">Chapter 3</div>
<h1>The Windows desktop app</h1> <h1>The Windows desktop app</h1>
<p class="lede">An optional, self-contained Windows build of the same application: no Node install, no account, no browser chrome. It is a folder you can copy to another PC, or an installer that creates shortcuts.</p> <p class="lede">An optional, self-contained Windows build of the same application: no Node install, no account, no browser. It is a folder you can copy to another PC, or an installer that creates shortcuts. The app opens its own window and starts, imports and edits with the network disconnected.</p>
<h2>What is in the folder</h2> <h2>What is in the folder</h2>
<table> <table>
<thead><tr><th style="width:34%">Item</th><th>Purpose</th></tr></thead> <thead><tr><th style="width:34%">Item</th><th>Purpose</th></tr></thead>
<tbody> <tbody>
<tr><td><code>Luminary.exe</code> or <code>Luminary.cmd</code></td><td>The launcher: starts the server hidden, waits for health, opens the window. <code>Luminary.vbs</code> does the same with no console window at all.</td></tr> <tr><td><code>Luminary.exe</code> or <code>Luminary.cmd</code></td><td>The launcher: starts the local engine hidden, waits for health, opens the window. <code>Luminary.exe</code> needs no console and no Windows Script Host; <code>Luminary.vbs</code> and <code>Luminary.cmd</code> are fallbacks.</td></tr>
<tr><td><code>LuminaryWindow.exe</code></td><td>The native window (WebView2). The launcher opens it; starting it directly also hands off to the launcher, so it opens in desktop mode.</td></tr> <tr><td><code>LuminaryWindow.exe</code></td><td>The native window (WebView2). The launcher opens it; starting it directly also hands off to the launcher, so it opens in desktop mode.</td></tr>
<tr><td><code>Luminary.ps1</code></td><td>The logic behind the launchers: preflight, port choice, health wait, repair, stop, status.</td></tr> <tr><td><code>Luminary.ps1</code></td><td>The logic behind the launchers: preflight, port choice, health wait, repair, stop, status.</td></tr>
<tr><td><code>node.exe</code></td><td>The bundled Node 24 runtime. Nothing is installed system-wide.</td></tr> <tr><td><code>node.exe</code></td><td>The bundled Node 24 runtime. Nothing is installed system-wide.</td></tr>
<tr><td><code>app\</code></td><td><code>server\</code>, <code>dist\</code> and production <code>node_modules\</code> — the unchanged application.</td></tr> <tr><td><code>app\</code></td><td><code>server\</code>, <code>dist\</code> and production <code>node_modules\</code> — the unchanged application.</td></tr>
<tr><td><code>Stop Luminary.cmd</code></td><td>Stops the server started from this folder.</td></tr> <tr><td><code>Stop Luminary.cmd</code></td><td>Stops the local engine this folder started (<code>Luminary.exe -Stop</code> does the same from the Start menu).</td></tr>
<tr><td><code>version.txt</code></td><td>Version, commit, build time, Node build and SHA-256 of <code>node.exe</code>.</td></tr> <tr><td><code>version.txt</code></td><td>Version, commit, build time, Node build and SHA-256 of <code>node.exe</code>.</td></tr>
</tbody> </tbody>
</table> </table>
@@ -392,10 +392,10 @@
<ol class="steps"> <ol class="steps">
<li>Copy the folder (or the ZIP) to the PC — for example <code>D:\Apps\Luminary</code>.</li> <li>Copy the folder (or the ZIP) to the PC — for example <code>D:\Apps\Luminary</code>.</li>
<li>Double-click <code>Luminary.cmd</code> (or <code>Luminary.vbs</code> for no console window; <code>Luminary.exe</code> in the Go build). Windows SmartScreen may warn because the build is unsigned: <b>More info → Run anyway</b>.</li> <li>Double-click <code>Luminary.cmd</code> (or <code>Luminary.vbs</code> for no console window; <code>Luminary.exe</code> in the Go build). Windows SmartScreen may warn because the build is unsigned: <b>More info → Run anyway</b>.</li>
<li>The first launch creates <code>%LOCALAPPDATA%\Luminary\data</code>, starts the server on a free port and opens the window.</li> <li>The first launch creates <code>%LOCALAPPDATA%\Luminary\data</code>, starts the local engine on a free port and opens the window.</li>
<li>Import a shoot. There is no sign-in screen: the app runs in single-user mode with one local administrator.</li> <li>Import a shoot. There is no sign-in screen: the app runs in single-user mode with one local administrator.</li>
</ol> </ol>
<p>The installer build (<code>Luminary-Setup.exe</code>) does the same into <code>Program Files</code>, adds Start-menu and desktop shortcuts with the Luminary icon, and registers an uninstaller. The data directory is deliberately kept out of <code>Program Files</code>, so uninstalling leaves the catalogue in place.</p> <p>The installer (<code>Luminary-Setup.exe</code>) does the same for your account into <code>%LOCALAPPDATA%\Programs\Luminary</code> — no administrator prompt — adds Start-menu and desktop shortcuts with the Luminary icon, and registers an uninstaller. Its <b>Start Luminary</b> tick, the shortcuts and start-at-login all launch <code>Luminary.exe</code> directly. The data directory is deliberately kept outside the program folder, so uninstalling leaves the catalogue in place.</p>
<h2>Everyday commands</h2> <h2>Everyday commands</h2>
<table> <table>
@@ -404,22 +404,23 @@
<tr><td><code>Luminary.cmd -Status</code></td><td>Prints the running state, the port and the data folder.</td></tr> <tr><td><code>Luminary.cmd -Status</code></td><td>Prints the running state, the port and the data folder.</td></tr>
<tr><td><code>Luminary.cmd -Verify</code></td><td>Checks every file the launcher needs, including the SHA-256 of <code>node.exe</code>. Exit 0 is good.</td></tr> <tr><td><code>Luminary.cmd -Verify</code></td><td>Checks every file the launcher needs, including the SHA-256 of <code>node.exe</code>. Exit 0 is good.</td></tr>
<tr><td><code>Luminary.cmd -Repair</code></td><td>Re-downloads a missing or corrupt <code>node.exe</code> and verifies the hash before installing it.</td></tr> <tr><td><code>Luminary.cmd -Repair</code></td><td>Re-downloads a missing or corrupt <code>node.exe</code> and verifies the hash before installing it.</td></tr>
<tr><td><code>Luminary.cmd -Stop</code></td><td>Stops the server this folder started; refuses to kill an unrelated process on the port.</td></tr> <tr><td><code>Luminary.exe -Stop</code></td><td>Stops the local engine this folder started; refuses to kill an unrelated process on the port. <code>Luminary.cmd -Stop</code> does the same.</td></tr>
<tr><td><code>Luminary.cmd -Browser</code></td><td>Skips the native window and opens the default browser instead.</td></tr> <tr><td><code>Luminary.cmd -Browser</code></td><td>Skips the native window and opens the default browser instead.</td></tr>
</tbody> </tbody>
</table> </table>
<h2>How it behaves</h2> <h2>How it behaves</h2>
<ul> <ul>
<li><b>Window choice</b> — <code>LuminaryWindow.exe</code> (native, own taskbar icon) first, then Edge or Chrome in <code>--app</code> mode, then the default browser.</li> <li><b>Window choice</b> — <code>LuminaryWindow.exe</code> (native, own taskbar icon) first; only if that is missing does it use Chrome, then Edge, in <code>--app</code> mode, and the default browser last. No browser profile or Microsoft account is involved in the native window.</li>
<li><b>Port</b> — the preferred port is tried first; if it is taken the launcher finds a free one and records it, so the shortcut always reaches the right instance.</li> <li><b>Port</b> — the preferred port is tried first; if it is taken the launcher finds a free one and records it, so the shortcut always reaches the right instance.</li>
<li><b>Second launch</b> — if the server is already up and healthy, the launcher reuses it instead of starting another.</li> <li><b>Second launch</b> — if the local engine is already up and healthy, the launcher reuses it instead of starting another.</li>
<li><b>Offline</b> — the engine listens on <code>127.0.0.1</code> only. The launcher waits for it over a direct loopback socket and the window ignores system proxies, so unplugging the network does not stop it starting, importing or editing.</li>
<li><b>Logs</b> — <code>%LOCALAPPDATA%\Luminary\data\logs\server.out.log</code> and <code>server.err.log</code>.</li> <li><b>Logs</b> — <code>%LOCALAPPDATA%\Luminary\data\logs\server.out.log</code> and <code>server.err.log</code>.</li>
<li><b>Read-only media</b> — logs and runtime state fall back to <code>%LOCALAPPDATA%</code> when the bundle folder cannot be written.</li> <li><b>Read-only media</b> — logs and runtime state fall back to <code>%LOCALAPPDATA%</code> when the bundle folder cannot be written.</li>
</ul> </ul>
<div class="note"> <div class="note">
<b>Starting the window directly.</b> Double-clicking <code>LuminaryWindow.exe</code> does not open a signed-out page. It hands off to the launcher, which starts the local server in desktop mode and reopens the window signed in. The launcher remains the recommended entry point — <code>Luminary.cmd</code> or <code>Luminary.vbs</code> (or <code>Luminary.exe</code> when the Go build is used). <b>Starting the window directly.</b> Double-clicking <code>LuminaryWindow.exe</code> does not open a signed-out page. It hands off to the launcher, which starts the local engine in desktop mode and reopens the window signed in. The launcher remains the recommended entry point — <code>Luminary.cmd</code> or <code>Luminary.vbs</code> (or <code>Luminary.exe</code> when the Go build is used).
</div> </div>
<div class="note"> <div class="note">
@@ -427,7 +428,7 @@
</div> </div>
<div class="warn note"> <div class="warn note">
<b>WebView2.</b> The native window uses the Evergreen WebView2 runtime that ships with Windows 10/11. If a machine lacks it, the launcher falls back to an Edge or Chrome app window — the application still runs, only the dedicated window shell is skipped. <b>WebView2.</b> The native window uses the Evergreen WebView2 runtime that ships with Windows 10/11. If a machine lacks it, the launcher falls back to a Chrome or Edge app window — the application still runs, only the dedicated window shell is skipped.
</div> </div>
</section> </section>
@@ -439,7 +440,7 @@
<figure> <figure>
<img src="img/10-import.jpg" alt="The import dialog"> <img src="img/10-import.jpg" alt="The import dialog">
<figcaption><b>Figure 1.</b> The import dialog. The event picker names the destination, the summary counts the batch, and the note confirms the server is ready to demosaic raws.</figcaption> <figcaption><b>Figure 1.</b> The import dialog. The event picker names the destination, the summary counts the batch, and the note confirms the local engine is ready to demosaic raws on this PC.</figcaption>
</figure> </figure>
<h2>Adding files</h2> <h2>Adding files</h2>
@@ -457,14 +458,14 @@
<thead><tr><th style="width:34%">Type</th><th>Behaviour</th></tr></thead> <thead><tr><th style="width:34%">Type</th><th>Behaviour</th></tr></thead>
<tbody> <tbody>
<tr><td>JPEG, PNG, WebP, AVIF</td><td>Decoded in the browser. EXIF camera, lens, ISO, aperture, shutter and focal length are read when present.</td></tr> <tr><td>JPEG, PNG, WebP, AVIF</td><td>Decoded in the browser. EXIF camera, lens, ISO, aperture, shutter and focal length are read when present.</td></tr>
<tr><td>TIFF (.tif, .tiff)</td><td>Decoded on the server into an editable JPEG proxy, because browsers have no TIFF decoder. The original TIFF is stored untouched and the full-resolution proxy drives the editor and export.</td></tr> <tr><td>TIFF (.tif, .tiff)</td><td>Decoded by the local engine (or the team server) into an editable JPEG proxy, because browsers have no TIFF decoder. The original TIFF is stored untouched and the full-resolution proxy drives the editor and export.</td></tr>
<tr><td>Camera raw — CR2, CR3, NEF, ARW, ORF, RW2, RAF, DNG, PEF, SRW, 3FR and 20 more</td><td>Sent to the server, demosaiced with LibRaw, stored as the original plus an editable JPEG proxy and a 16-bit sidecar.</td></tr> <tr><td>Camera raw — CR2, CR3, NEF, ARW, ORF, RW2, RAF, DNG, PEF, SRW, 3FR and 20 more</td><td>Sent to the local engine (or the team server), demosaiced with LibRaw on this PC, stored as the original plus an editable JPEG proxy and a 16-bit sidecar. Nothing is uploaded anywhere.</td></tr>
</tbody> </tbody>
</table> </table>
<p>A progress bar names the file being read. Failures are listed individually with the reason while the successes are kept; an unreadable raw usually means the server is offline or LibRaw does not support that camera.</p> <p>A progress bar names the file being read. Failures are listed individually with the reason while the successes are kept; an unreadable raw usually means the local engine is not running or LibRaw does not support that camera.</p>
<h2>Tethering instead of a card reader</h2> <h2>Tethering instead of a card reader</h2>
<p>An event can watch a folder on the server. Point a capture app or a transfer folder at <code>&lt;data&gt;\tether\&lt;event id&gt;</code>; the open editor polls it, imports each new JPEG, TIFF, WebP or raw through the normal path, and only deletes the file after the client confirms. Closing the tab loses nothing — the files wait in the folder.</p> <p>An event can watch a folder on the engine. Point a capture app or a transfer folder at <code>&lt;data&gt;\tether\&lt;event id&gt;</code>; the open editor polls it, imports each new JPEG, TIFF, WebP or raw through the normal path, and only deletes the file after the client confirms. Closing the tab loses nothing — the files wait in the folder.</p>
<div class="note"> <div class="note">
<b>Try this.</b> Import ten frames, name the event after the shoot, then drag the whole event onto another in the sidebar. The photos move as metadata; no file is copied or re-encoded. <b>Try this.</b> Import ten frames, name the event after the shoot, then drag the whole event onto another in the sidebar. The photos move as metadata; no file is copied or re-encoded.
@@ -483,7 +484,7 @@
</figure> </figure>
<h2>The sidebar</h2> <h2>The sidebar</h2>
<p><b>All photos</b> is the whole catalogue; <b>Trash</b> holds deleted photos until you empty it (restore, delete permanently, or empty all). Each event shows its photo count. <b>+</b> creates an event; drag one event onto another to move its photos; the footer reports whether a server is connected and who you are signed in as.</p> <p><b>All photos</b> is the whole catalogue; <b>Trash</b> holds deleted photos until you empty it (restore, delete permanently, or empty all). Each event shows its photo count. <b>+</b> creates an event; drag one event onto another to move its photos; the footer reports whether a team server is connected and who you are signed in as.</p>
<h2>The filter bar</h2> <h2>The filter bar</h2>
<figure> <figure>
@@ -722,7 +723,9 @@
<tr><td>Sharpen — Detail</td><td>How much fine structure is included; lower values protect smooth areas.</td></tr> <tr><td>Sharpen — Detail</td><td>How much fine structure is included; lower values protect smooth areas.</td></tr>
<tr><td>Noise reduction — Luminance</td><td>Smooths luminance noise at the cost of fine detail.</td></tr> <tr><td>Noise reduction — Luminance</td><td>Smooths luminance noise at the cost of fine detail.</td></tr>
<tr><td>Noise reduction — Detail</td><td>How much texture survives the smoothing.</td></tr> <tr><td>Noise reduction — Detail</td><td>How much texture survives the smoothing.</td></tr>
<tr><td>Denoise</td><td>Detail-preserving pass that runs on the server for difficult high-ISO frames; the result is cached per parameter set.</td></tr> <tr><td>Denoise</td><td>Detail-preserving pass that runs in the local engine (or the team server) for difficult high-ISO frames; the result is cached per model, so switching back to a model you already rendered is instant.</td></tr>
<tr><td>AI denoise — Model</td><td><b>Guided</b> (default, fastest, keeps the most fine texture), <b>SCUNet</b> (learned model, removes the most grain and smooths more) or <b>NLM</b> (non-local means, between the two). Pick one and press Generate; the model is saved with the photo.</td></tr>
<tr><td>AI denoise — Amount</td><td>Blends the rendered result into the frame. The engine always renders at full strength, so the slider is instant and never re-runs the model.</td></tr>
</tbody> </tbody>
</table> </table>
@@ -852,11 +855,11 @@
<figure> <figure>
<img src="img/08-presets.jpg" alt="The preset rail"> <img src="img/08-presets.jpg" alt="The preset rail">
<figcaption><b>Figure 14.</b> The preset rail with search, category filter, the look variants (Stock, Push +1, Pull −1, Warm split, Cool split) and tiles rendered from your own photo at your current crop.</figcaption> <figcaption><b>Figure 14.</b> The preset rail with search, category filter, the look variants (Stock, Push +1, Pull −1, Warm split, Cool split) and tiles rendered from your own photo at your current crop, tone, colour and white balance.</figcaption>
</figure> </figure>
<h2>Presets</h2> <h2>Presets</h2>
<p>Groups include Essentials, Film, Warm and Cinematic. The variant row re-renders the whole rail a stop brighter or darker, or with the split-tone reversed. Click a tile to apply: it replaces the develop parameters but leaves crop and rotation alone, because those belong to the frame. <b>+</b> saves the current look as your own preset with a rendered preview.</p> <p>Groups include Essentials, Film, Warm and Cinematic. The variant row re-renders the whole rail a stop brighter or darker, or with the split-tone reversed. Click a tile to apply: the look's tone and colour replace the develop parameters, while crop and rotation stay, because those belong to the frame. The white balance you set is kept as the base the look is graded over — the stock's own warmth or coolness is added on top of it, so correct a difficult frame first and the film still sits over that correction. Switching looks swaps that cast instead of stacking one stock's cast on the last one's. Because the look adds its cast to your correction, the Light panel prints both: the look's own cast and the final balance the photo is graded at, right under Temp and Tint. Every tile is rendered over the grade the photo has now, so the thumbnail is what the click produces. <b>+</b> saves the current look as your own preset with a rendered preview.</p>
<h2>History, undo and redo</h2> <h2>History, undo and redo</h2>
<p>Every adjustment is recorded with a label. <b>History</b> in the left rail restores any step; <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps back, <kbd>⇧</kbd> + <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps forward. History is per photo and saved with the catalogue.</p> <p>Every adjustment is recorded with a label. <b>History</b> in the left rail restores any step; <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps back, <kbd>⇧</kbd> + <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps forward. History is per photo and saved with the catalogue.</p>
@@ -928,7 +931,7 @@
<table> <table>
<thead><tr><th style="width:26%">Option</th><th>What it does</th></tr></thead> <thead><tr><th style="width:26%">Option</th><th>What it does</th></tr></thead>
<tbody> <tbody>
<tr><td>Format</td><td>JPEG, PNG, WebP or uncompressed 16-bit TIFF. JPEG and WebP expose quality; PNG and TIFF are lossless.</td></tr> <tr><td>Format</td><td>JPEG, PNG, WebP, JPEG XL or uncompressed 16-bit TIFF. JPEG, WebP and JPEG XL expose quality; JPEG XL also has a lossless switch; PNG and TIFF are lossless.</td></tr>
<tr><td>Resize</td><td>Full resolution, a long-edge size in pixels, or a percentage of the cropped frame.</td></tr> <tr><td>Resize</td><td>Full resolution, a long-edge size in pixels, or a percentage of the cropped frame.</td></tr>
<tr><td>Quality</td><td>Encoder quality, 40–100. 90–95 is visually lossless for most photographs.</td></tr> <tr><td>Quality</td><td>Encoder quality, 40–100. 90–95 is visually lossless for most photographs.</td></tr>
<tr><td>File name</td><td>Template with <code>{name}</code>, <code>{date}</code>, <code>{time}</code> and <code>{index}</code>; the first result is previewed underneath.</td></tr> <tr><td>File name</td><td>Template with <code>{name}</code>, <code>{date}</code>, <code>{time}</code> and <code>{index}</code>; the first result is previewed underneath.</td></tr>
@@ -1190,7 +1193,7 @@
<b>If something looks wrong, press <kbd>?</kbd> and compare.</b> The shortcut sheet is generated from the same map the keyboard uses, so if a key is listed there it is live. <b>If something looks wrong, press <kbd>?</kbd> and compare.</b> The shortcut sheet is generated from the same map the keyboard uses, so if a key is listed there it is live.
</div> </div>
<div class="end">Luminary User Guide · Version 1.1 · Screenshots captured from a live 868-photo catalog at 1500 × 940.</div> <div class="end">Luminary User Guide · Version 1.3 · Screenshots captured from a live 868-photo catalog at 1500 × 940.</div>
</section> </section>
<!-- ============================== APPENDIX A ============================== --> <!-- ============================== APPENDIX A ============================== -->
@@ -1212,7 +1215,8 @@
</table> </table>
<h2>Export formats</h2> <h2>Export formats</h2>
<p>JPEG, PNG, WebP and uncompressed 16-bit TIFF, at full resolution, a long edge, or a percentage of the cropped frame. Output dimensions always reflect the crop and rotation; colour space is sRGB, Display P3 or Adobe RGB with a generated ICC profile.</p> <p>JPEG, PNG, WebP, JPEG XL and uncompressed 16-bit TIFF, at full resolution, a long edge, or a percentage of the cropped frame. Output dimensions always reflect the crop and rotation; colour space is sRGB, Display P3 or Adobe RGB with a generated ICC profile.</p>
<p>JPEG XL is exported at 8-bit in sRGB, either lossy (quality 40–100) or lossless, using libjxl compiled to WebAssembly inside the app — the file is encoded on this computer and nothing is uploaded. There is no embedded ICC profile or XMP metadata in a JXL export yet; use JPEG or 16-bit TIFF when you need those. Chrome 155+, Firefox 158+ and Safari 17+ open .jxl files; Microsoft Edge does not display them yet.</p>
<h2>Badges on a card</h2> <h2>Badges on a card</h2>
<table> <table>
@@ -1244,7 +1248,7 @@
<tr><td><code>previews/&lt;id&gt;.p16.png</code></td><td>16-bit sidecar: the decoded samples before JPEG quantisation.</td></tr> <tr><td><code>previews/&lt;id&gt;.p16.png</code></td><td>16-bit sidecar: the decoded samples before JPEG quantisation.</td></tr>
<tr><td><code>previews/&lt;id&gt;.t16.png</code></td><td>Camera-native grid thumbnail generated from the sidecar.</td></tr> <tr><td><code>previews/&lt;id&gt;.t16.png</code></td><td>Camera-native grid thumbnail generated from the sidecar.</td></tr>
<tr><td><code>thumbs/&lt;id&gt;.jpg</code></td><td>Grid thumbnail.</td></tr> <tr><td><code>thumbs/&lt;id&gt;.jpg</code></td><td>Grid thumbnail.</td></tr>
<tr><td><code>denoised/&lt;id&gt;.&lt;hash&gt;.jpg</code></td><td>Cached denoise result per parameter set.</td></tr> <tr><td><code>denoised/&lt;id&gt;.&lt;hash&gt;.jpg</code></td><td>Cached denoise result, one per model (Guided, SCUNet, NLM) per photo.</td></tr>
<tr><td><code>proofs/</code>, <code>proofThumbs/</code></td><td>Published client proofs and their thumbnails.</td></tr> <tr><td><code>proofs/</code>, <code>proofThumbs/</code></td><td>Published client proofs and their thumbnails.</td></tr>
<tr><td><code>tether/&lt;event&gt;/</code></td><td>The tethered capture drop folder.</td></tr> <tr><td><code>tether/&lt;event&gt;/</code></td><td>The tethered capture drop folder.</td></tr>
<tr><td><code>secret.key</code></td><td>Generated key sealing SMTP and API credentials. Back it up with the database.</td></tr> <tr><td><code>secret.key</code></td><td>Generated key sealing SMTP and API credentials. Back it up with the database.</td></tr>
+7 -7
View File
@@ -51,8 +51,8 @@ Output:
``` ```
<out>/ <out>/
Luminary-0.5.1-linux-x64.tar.gz portable bundle Luminary-0.5.4-linux-x64.tar.gz portable bundle
Luminary-0.5.1-linux-amd64.deb Ubuntu package, built from the same bundle Luminary-0.5.4-linux-amd64.deb Ubuntu package, built from the same bundle
stage/Luminary/ the unpacked bundle (kept for inspection) stage/Luminary/ the unpacked bundle (kept for inspection)
cache/node-v24.22.2-linux-x64.tar.gz cache/node-v24.22.2-linux-x64.tar.gz
cache/SHASUMS256-v24.22.2.txt cache/SHASUMS256-v24.22.2.txt
@@ -72,7 +72,7 @@ catalog still live in `~/.local/share/luminary`, so removing or upgrading the
package never touches them: package never touches them:
```bash ```bash
sudo apt install ./Luminary-0.5.1-linux-amd64.deb sudo apt install ./Luminary-0.5.4-linux-amd64.deb
luminary # or launch Luminary from the applications menu luminary # or launch Luminary from the applications menu
``` ```
@@ -84,7 +84,7 @@ with `sudo apt remove luminary`; `sudo apt purge luminary` also removes
Or stay portable — nothing installed, nothing to root: Or stay portable — nothing installed, nothing to root:
```bash ```bash
tar -xzf Luminary-0.5.1-linux-x64.tar.gz tar -xzf Luminary-0.5.4-linux-x64.tar.gz
cd Luminary cd Luminary
./luminary # starts desktop mode and opens the app window ./luminary # starts desktop mode and opens the app window
./install.sh # optional: add Luminary to the applications menu ./install.sh # optional: add Luminary to the applications menu
@@ -187,9 +187,9 @@ check (the launcher runs with `LUMINARY_WINDOW=none` during the test).
```bash ```bash
cd <out> cd <out>
sha256sum Luminary-0.5.1-linux-x64.tar.gz sha256sum Luminary-0.5.4-linux-x64.tar.gz
tar -tzf Luminary-0.5.1-linux-x64.tar.gz | grep -E 'luminary$|runtime/bin/node$|app/server/index.mjs$' tar -tzf Luminary-0.5.4-linux-x64.tar.gz | grep -E 'luminary$|runtime/bin/node$|app/server/index.mjs$'
tar -xzf Luminary-0.5.1-linux-x64.tar.gz -C /tmp/luminary-check tar -xzf Luminary-0.5.4-linux-x64.tar.gz -C /tmp/luminary-check
/tmp/luminary-check/Luminary/luminary --verify /tmp/luminary-check/Luminary/luminary --verify
``` ```
+72
View File
@@ -256,6 +256,78 @@ else
check '--status reports stopped' 1 check '--status reports stopped' 1
fi fi
say ''
say 'Offline import (proxy unreachable)'
# Every proxy variable points at a black hole, so a request that consults the
# system proxy fails instead of reaching 127.0.0.1. That is the shape of the
# bug where an import with the network unplugged reported that it could not
# reach the engine: the engine was fine, the request was routed through a proxy.
PROXY_VARS=(HTTP_PROXY HTTPS_PROXY ALL_PROXY http_proxy https_proxy all_proxy GLOBAL_AGENT_HTTP_PROXY)
for var in "${PROXY_VARS[@]}"; do export "$var=http://10.255.255.1:9"; done
unset NO_PROXY no_proxy
check 'app window bypasses proxies' "$(grep -q -- '--no-proxy-server' "$BUNDLE/luminary" && echo 0 || echo 1)"
"$BUNDLE/luminary" >"$WORK_DIR/offline-start.txt" 2>&1
offline_start=$?
check 'launcher starts with the proxy unreachable' "$offline_start" "$(head -n 1 "$WORK_DIR/offline-start.txt")"
OFFLINE_URL=""
if [ -f "$LUMINARY_DATA/runtime.json" ]; then
OFFLINE_URL="http://127.0.0.1:$("$NODE" -p "JSON.parse(require('fs').readFileSync('$LUMINARY_DATA/runtime.json','utf8')).port")"
check 'runtime.json written offline' 0
else
check 'runtime.json written offline' 1 "$LUMINARY_DATA/runtime.json"
fi
if [ -n "$OFFLINE_URL" ]; then
code="$(http GET "$OFFLINE_URL/api/health")"
check 'health answers offline' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
# An import is an upload, a decode in the bundle and a preview read. TIFF
# takes the same server path as camera raw, so this exercises the real thing
# without shipping a raw fixture in the bundle.
"$NODE" -e '
const path = require("node:path");
const sharp = require(path.join(process.argv[1], "app", "node_modules", "sharp"));
sharp({ create: { width: 8, height: 8, channels: 3, background: { r: 200, g: 100, b: 50 } } })
.tiff()
.toFile(process.argv[2])
.then(() => process.exit(0))
.catch(() => process.exit(1));
' "$BUNDLE" "$WORK_DIR/offline-smoke.tiff"
check 'prepared a TIFF to import' "$?"
upload_status="$("$NODE" -e '
const fs = require("node:fs");
const [url, file, out] = process.argv.slice(-3);
fetch(url, { method: "POST", headers: { "Content-Type": "image/tiff" }, body: fs.readFileSync(file) })
.then(async (r) => { fs.writeFileSync(out, await r.text()); process.stdout.write(String(r.status)); })
.catch(() => process.stdout.write("0"));
' "$OFFLINE_URL/api/photos/smoke-offline/original?name=offline-smoke.tiff&mime=image%2Ftiff" "$WORK_DIR/offline-smoke.tiff" "$BODY")"
# A new upload is created (201); replacing one answers 200.
case "$upload_status" in
200|201) upload_ok=0 ;;
*) upload_ok=1 ;;
esac
check 'import upload accepted offline' "$upload_ok" "HTTP $upload_status"
preview="$(jget previewUrl)"
check 'decoded proxy offered offline' $([ -n "$preview" ] && echo 0 || echo 1) "$preview"
if [ -n "$preview" ]; then
case "$preview" in
http*) preview_url="$preview" ;;
*) preview_url="$OFFLINE_URL$preview" ;;
esac
code="$(http GET "$preview_url")"
check 'preview readable offline' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
fi
fi
"$BUNDLE/luminary" --stop >/dev/null 2>&1
check 'stopped the offline run' 0
for var in "${PROXY_VARS[@]}"; do unset "$var"; done
say '' say ''
say 'Window' say 'Window'
skip 'app window opens' 'visual check; the launcher opened nothing during this run' skip 'app window opens' 'visual check; the launcher opened nothing during this run'
+15 -2
View File
@@ -237,11 +237,14 @@ function installLinuxDeps(bundle) {
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json')); cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
log('deps', 'npm ci --omit=dev --os=linux --cpu=x64 (sharp linux-x64 prebuild)'); log('deps', 'npm ci --omit=dev --os=linux --cpu=x64 (sharp linux-x64 prebuild)');
// --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the // --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the
// prebuilt binary through optionalDependencies. // prebuilt binary through optionalDependencies. ONNXRUNTIME_NODE_INSTALL=skip
// also keeps onnxruntime-node's postinstall from pulling the CUDA libraries;
// the package already ships its CPU binaries.
run( run(
NPM, NPM,
['ci', '--omit=dev', '--os=linux', '--cpu=x64', '--no-audit', '--no-fund', '--ignore-scripts'], ['ci', '--omit=dev', '--os=linux', '--cpu=x64', '--no-audit', '--no-fund', '--ignore-scripts'],
appDir, appDir,
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
); );
// .bin shims are for an interactive shell, not for `node server/index.mjs`. // .bin shims are for an interactive shell, not for `node server/index.mjs`.
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true }); rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
@@ -438,7 +441,7 @@ Updating: stop Luminary, replace app/ and runtime/ from a newer bundle, start
again. The data folder is outside the bundle and is untouched. again. The data folder is outside the bundle and is untouched.
Notes Notes
- The server listens on 127.0.0.1 only. Set HOST=0.0.0.0 when starting it - The local engine listens on 127.0.0.1 only. Set HOST=0.0.0.0 when starting it
directly with node if client proofing galleries must reach other devices. directly with node if client proofing galleries must reach other devices.
- The app window is the browser's own app mode with a private profile, so it - The app window is the browser's own app mode with a private profile, so it
has no tabs or address bar. Some Wayland desktops ignore the requested has no tabs or address bar. Some Wayland desktops ignore the requested
@@ -529,6 +532,16 @@ function debCopyright() {
'License: MIT', 'License: MIT',
' The full MIT licence text is in /opt/luminary/LICENSE.', ' The full MIT licence text is in /opt/luminary/LICENSE.',
'', '',
'Files: opt/luminary/app/node_modules/onnxruntime-node/*',
'Copyright: Microsoft Corporation',
'License: MIT',
' ONNX Runtime; see /opt/luminary/THIRD_PARTY_NOTICES.md.',
'',
'Files: opt/luminary/app/server/denoise/scunet_color_25.onnx*',
'Copyright: Kai Zhang and SCUNet contributors',
'License: Apache-2.0',
' See /opt/luminary/THIRD_PARTY_NOTICES.md.',
'',
].join('\n'); ].join('\n');
} }
+6 -3
View File
@@ -1,13 +1,13 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Luminary desktop launcher for Linux. # Luminary desktop launcher for Linux.
# #
# Starts the bundled server in single-user desktop mode on a free loopback port, # Starts the bundled local engine in single-user desktop mode on a free loopback port,
# waits for /api/health, then opens the UI in a chromeless app window (Chrome, # waits for /api/health, then opens the UI in a chromeless app window (Chrome,
# Chromium, Edge, Brave or Vivaldi). Firefox, or the default browser, is the # Chromium, Edge, Brave or Vivaldi). Firefox, or the default browser, is the
# fallback. # fallback.
# #
# ./luminary start and open the window # ./luminary start and open the window
# ./luminary --stop stop the running server # ./luminary --stop stop the running local engine
# ./luminary --status report pid, URL, data folder and health # ./luminary --status report pid, URL, data folder and health
# ./luminary --browser open a normal browser tab instead # ./luminary --browser open a normal browser tab instead
# ./luminary --verify check that this is a complete bundle # ./luminary --verify check that this is a complete bundle
@@ -167,7 +167,7 @@ start() {
pid="$(cat "$PID_FILE" 2>/dev/null)" pid="$(cat "$PID_FILE" 2>/dev/null)"
if ! wait_health "$port"; then if ! wait_health "$port"; then
problem "the server did not answer on /api/health." problem "the local engine did not answer on /api/health."
problem "See $LOG_DIR/server.err.log, or run: cd \"$APP\" && \"$NODE\" server/index.mjs" problem "See $LOG_DIR/server.err.log, or run: cd \"$APP\" && \"$NODE\" server/index.mjs"
return 1 return 1
fi fi
@@ -237,12 +237,15 @@ open_window() {
while IFS= read -r name; do while IFS= read -r name; do
if browser="$(command -v "$name" 2>/dev/null)"; then if browser="$(command -v "$name" 2>/dev/null)"; then
say "Opening the app window with $name" say "Opening the app window with $name"
# --no-proxy-server: the window only ever loads 127.0.0.1, and an
# offline machine cannot resolve the system proxy it would otherwise use.
setsid "$browser" \ setsid "$browser" \
--app="$url" \ --app="$url" \
--user-data-dir="$DATA_DIR/window-profile" \ --user-data-dir="$DATA_DIR/window-profile" \
--class=Luminary \ --class=Luminary \
--no-first-run \ --no-first-run \
--no-default-browser-check \ --no-default-browser-check \
--no-proxy-server \
>/dev/null 2>&1 & >/dev/null 2>&1 &
return 0 return 0
fi fi
+5 -5
View File
@@ -3,8 +3,8 @@
`node linux/build.mjs --skip-build --publish` drops the finished artifacts here: `node linux/build.mjs --skip-build --publish` drops the finished artifacts here:
``` ```
Luminary-0.5.1-linux-x64.tar.gz portable bundle Luminary-0.5.3.1-linux-x64.tar.gz portable bundle
Luminary-0.5.1-linux-amd64.deb Ubuntu package Luminary-0.5.3.1-linux-amd64.deb Ubuntu package
SHA256SUMS.txt SHA256SUMS.txt
``` ```
@@ -16,11 +16,11 @@ Verify a copy with:
```bash ```bash
sha256sum -c SHA256SUMS.txt sha256sum -c SHA256SUMS.txt
tar -tzf Luminary-0.5.1-linux-x64.tar.gz | head tar -tzf Luminary-0.5.3.1-linux-x64.tar.gz | head
dpkg-deb --info Luminary-0.5.1-linux-amd64.deb dpkg-deb --info Luminary-0.5.3.1-linux-amd64.deb
``` ```
On Ubuntu the easiest install is `sudo apt install ./Luminary-0.5.1-linux-amd64.deb`, On Ubuntu the easiest install is `sudo apt install ./Luminary-0.5.3.1-linux-amd64.deb`,
which adds Luminary to the applications menu. The portable route is to extract which adds Luminary to the applications menu. The portable route is to extract
the whole tarball and run `./luminary` from the extracted `Luminary` folder; the whole tarball and run `./luminary` from the extracted `Luminary` folder;
`./install.sh` adds that copy to the applications menu. `./install.sh` adds that copy to the applications menu.
+4 -2
View File
@@ -1,2 +1,4 @@
7b2f91d603b49aa19734e681278a16f8024018c618b1c342d2607c75a2e6722f Luminary-0.5.1-linux-x64.tar.gz 3b2a7ac1d5b0057ce0d3796b5e2a57024a5d7d655800ed55245c2f00141827fd Luminary-0.5.4-linux-x64.tar.gz
5649939b748946409a99d6e8e99a4d5a5613f7602458b23d9af23ef9b7f65d04 Luminary-0.5.1-linux-amd64.deb 45043c4c71003ccf210b7ee5ae8c45a58406aa526fa13e7fdb6e26f89b8c52ec Luminary-0.5.4-linux-amd64.deb
895c6c5cffe47a17c18690fb55746d10c225e376721d70f233b10d635e5f2255 Luminary-0.5.4.1-linux-x64.tar.gz
d4aae7f9fb91a3c5eb66de284f8ed39977dd0b73d76e622e94d3b9ec98923e58 Luminary-0.5.4.1-linux-amd64.deb
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>Luminary</string>
<key>CFBundleDisplayName</key>
<string>Luminary</string>
<key>CFBundleIdentifier</key>
<string>__BUNDLE_ID__</string>
<key>CFBundleVersion</key>
<string>__VERSION__</string>
<key>CFBundleShortVersionString</key>
<string>__VERSION__</string>
<key>CFBundleExecutable</key>
<string>Luminary</string>
<key>CFBundleIconFile</key>
<string>Luminary</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>LSMinimumSystemVersion</key>
<string>__MIN_OS__</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.photography</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>MIT licensed. Copyright 2026 Brian Hursey.</string>
</dict>
</plist>
+63
View File
@@ -0,0 +1,63 @@
Luminary for macOS
==================
Install
1. Open the disk image (or unzip the archive).
2. Drag Luminary to the Applications folder.
3. Eject the disk image, then open Luminary from Applications.
First launch (unsigned build)
This build is not notarized by Apple, so macOS will say it cannot verify the
app. That is expected: it means nobody paid Apple's yearly fee, not that
anything is wrong with the file.
1. Double-click Luminary and dismiss the warning with Done.
2. Open System Settings > Privacy & Security.
3. Scroll to Security and click Open Anyway, then authenticate.
macOS remembers the choice, so this is a one-time step. The Open Anyway
button only appears for about an hour after the blocked attempt; if it is
missing, double-click the app again and go back.
What it needs
- macOS 11 Big Sur or newer (the build records its own minimum in
Info.plist; 11.0 for the Node 22 build, 13.5 for the Node 24 build).
- A browser with WebAssembly and WebGL2. Chrome or Edge is used for the app
window when installed; otherwise the default browser opens a normal tab.
- Nothing else. Node.js is inside the app, so no Homebrew, no npm install
and no administrator password are needed for day-to-day use.
Start, stop and status
Opening Luminary starts the local engine and opens the editor. Opening it
again reuses the running copy instead of starting a second one.
- Stop Luminary.command (next to the app in the disk image) stops it.
- The same commands are available from a terminal:
/Applications/Luminary.app/Contents/Resources/launcher.sh --status
/Applications/Luminary.app/Contents/Resources/launcher.sh --stop
(or run the app with --args --status: open -a Luminary --args --status)
Where your photos live
~/Library/Application Support/Luminary/data
That folder holds the SQLite catalog, the originals, previews and thumbnails.
Set LUMINARY_DATA before launching to keep it somewhere else, such as an
external drive. Back it up by copying the whole folder while Luminary is
stopped, including lumenroom.db, lumenroom.db-wal and lumenroom.db-shm.
Logs
~/Library/Application Support/Luminary/data/logs/server.out.log
~/Library/Application Support/Luminary/data/logs/server.err.log
Updating
Stop the local engine (Stop Luminary.command), drag the new Luminary.app over the
old one, and start it again. The data folder is outside the app and is not
touched. The catalog migrates itself on first start.
Notes
- The local engine listens on 127.0.0.1 only. For proofing galleries that
other devices should reach, run it yourself with HOST=0.0.0.0.
- The app window is Chrome or Edge in app mode, using its own profile in the
data folder, so it does not mix with your normal browsing. Set
LUMINARY_WINDOW=browser to open a normal tab instead.
- This build is single-user desktop mode: it signs in as a local admin
without a password and is not meant for several people sharing one Mac
account.
- The bundle is ad-hoc signed. If you rebuild it yourself with a Developer ID
certificate and notarize it, the first-launch step above disappears.
+186
View File
@@ -0,0 +1,186 @@
# macOS app (optional)
An additive, self-contained way to produce a double-clickable macOS app of
Luminary. The server and Docker workflow stay the source of truth: this folder
only *packages* the existing `dist/` + `server/` output, and the build writes
its artifacts **outside the checkout**.
## Isolation guarantees
1. **The packaging tree is additive.** There is no `package.json` script for
this, and no change to `Dockerfile`, `docker-compose.yml` or
`scripts/deploy.mjs`. Invoke it directly: `node macos/build.mjs`. The app
uses the same desktop mode the Windows launcher uses (`LUMINARY_LOCAL=1`),
which is off unless a launcher sets it.
2. **Artifacts live outside the repo** (default: `~/Library/Caches/luminary-macos`).
The script refuses an `--out` inside the checkout, because
`scripts/deploy.mjs` rsyncs the worktree to production and `docker build`
would pull the bundle into its context.
3. **The worktree must be clean outside `macos/`** before and after a build
(the untracked `logo.png` is tolerated). `--allow-dirty` overrides it.
4. **Nothing in the app changes at run time.** The bundle is the unchanged
`server/` + `dist/` + production `node_modules`, started with `PORT`, `HOST`,
`NODE_ENV` and `LUMINARY_DATA` — all variables the server already reads.
It must run on macOS: the build needs `clang`, `codesign`, `ditto`, `hdiutil`,
`sips` and `iconutil`. The Windows bundle is the one that cross-builds from
Linux.
## Quick start
On a fresh checkout run `npm ci` once: the UI build uses `vite` and `tsc` from
the dev dependencies, and the script copies the production dependencies into
the app itself.
```sh
node macos/build.mjs # host arch, Node 24, ad-hoc signature, zip + dmg
node macos/build.mjs --arch universal # arm64 + x86_64, both sharp slices
node macos/build.mjs --node v22.23.5 # minimum macOS 11.0 instead of 13.5
node macos/build.mjs --skip-build --sign none
```
Outputs:
```
~/Library/Caches/luminary-macos/
stage/Luminary.app
Luminary-0.5.3.1-mac-arm64.zip
Luminary-0.5.3.1-mac-arm64.dmg
cache/ # downloaded node tarballs, icon work
```
`--publish` copies the zip and dmg into `macos/releases/` with a
`SHA256SUMS.txt`, for transfer to a Mac. `.gitignore` keeps those archives out
of git.
## Bundle layout
```
Luminary.app/Contents/
Info.plist, PkgInfo
MacOS/Luminary native shim (main.c) -> execs the launcher
Resources/
launcher.sh start/stop/status/verify (bash)
Luminary.icns
version.txt, README-macos.txt
runtime/node official Node for the built architecture
app/
server/ unchanged, minus data/ and *.test.*
dist/ unchanged, including .br/.gz variants
node_modules/ production deps only (sharp for each slice)
package.json, LICENSE, THIRD_PARTY_NOTICES.md, licenses/
```
The main executable is a **Mach-O shim**, not a shell script. Apple treats
scripts in `Contents/MacOS` as resources, and the notary service rejects a
bundle whose main executable is not signed native code; the shim is a few lines
of C that execs `bash launcher.sh`, so the launcher stays editable without a
rebuild and the bundle can still be signed and notarized.
## Node and the minimum macOS version
| Node | Bundled runtime minimum | `LSMinimumSystemVersion` |
| --- | --- | --- |
| v22.18+ | macOS 11.0 | 11.0 |
| v24+ | macOS 13.5 | 13.5 |
Node 24's official macOS binaries are built against 13.5, so they cannot start
on Big Sur or Monterey; a macOS 11 build must bundle Node 22. Both lines run
this server: `node:sqlite` is unflagged from 22.13, type stripping (used by
`server/denoise-worker.mjs` importing a `.ts` pipeline) from 22.18, and the
HTTP integration suite passes under 22.23.5.
`--node-bin` uses a local binary instead of downloading one; the build warns if
`otool -L` shows libraries outside `/usr/lib` and `/System` (a Homebrew node
would drag Homebrew's ICU along and fail on a stock Mac).
## Signing and notarization
Three modes:
| `--sign` | What it does | Users see |
| --- | --- | --- |
| `adhoc` (default) | `codesign --sign -` on every Mach-O, then the bundle | “Apple could not verify …”, one-time Open Anyway |
| `none` | no signature | the same, and arm64 Macs may refuse to launch it |
| `developer-id` | signs each nested Mach-O with the Developer ID, hardened runtime and JIT entitlements on executables, then the bundle | no warning |
Notarization needs a paid Apple Developer Program membership:
```sh
xcrun notarytool store-credentials luminary \
--apple-id you@example.com --team-id TEAMID --password APP_SPECIFIC_PASSWORD
node macos/build.mjs --arch universal \
--sign developer-id --identity "Developer ID Application: Brian Hursey (TEAMID)" \
--notarize luminary --publish
```
The build submits the zip, staples the `.app`, rebuilds the zip, then creates the
dmg and submits and staples that too. `entitlements.plist` contains
`allow-jit`, `allow-unsigned-executable-memory` and `disable-library-validation`
— Node needs the first two under the hardened runtime, and sharp loads libvips
as a dylib, which library validation would otherwise reject.
Without the certificate everything still works; the first-launch instructions in
`README-macos.txt` cover the Gatekeeper step. macOS 15 and 26 removed the
Control-click → Open bypass, so that text names the System Settings path.
## Launcher behaviour
Same rules as the Windows launcher (`windows/launcher/DESIGN.md`):
- **No mutex.** `runtime.json` in the data folder records pid/port, and
`/api/health` is the liveness test: a healthy recorded port is reused, a stale
one is replaced.
- **Ports** 8787–8887, loopback only. The chosen port is passed as `PORT`.
- **Data** defaults to `~/Library/Application Support/Luminary/data`; an
existing `LUMINARY_DATA` wins. Logs go to `<data>/logs/`.
- **Window**: Chrome or Edge in `--app` mode with its own profile in the data
folder; `--browser` or `LUMINARY_WINDOW=browser` opens a normal tab; neither
installed falls back to the default browser.
- **Server lifetime**: detached, so closing the browser does not stop it and
reopening the app reuses it. `--stop` (and `Stop Luminary.command` next to the
app in the dmg) terminates it; `--status` prints pid, port, health and paths;
`--verify` checks the three files a complete bundle needs.
## Test checklist (on the Tahoe machine)
1. `node macos/build.mjs --arch universal --dmg` → zip and dmg exist; summary
prints arch, Node version, target and hashes.
2. `codesign --verify --deep --strict --verbose=2 stage/Luminary.app` → valid.
3. Copy the app out of the dmg, open it → browser/app window opens on the
editor, no sign-in screen (desktop mode).
4. Launch again while it runs → same port is reused, no second node process;
`pgrep -fl 'Resources/runtime/node'` shows one.
5. `--stop` → process gone, `runtime.json` removed; `--stop` again says
"not running".
6. Occupy 8787 with another listener → the app starts on 8788 and opens that
URL.
7. Import a raw, apply a film look, export → proves libraw WASM, sharp (dylibs
load under the signature) and the export path.
8. Denoise a photo → proves the `.ts` worker under the bundled Node.
9. Quit the browser, reopen the app → the same catalog opens; the data folder
holds the SQLite files.
10. `--verify` with a renamed `runtime/node` → exit 3 and a dialog, not a silent
failure.
11. Path with spaces / non-ASCII in `LUMINARY_DATA` → starts and writes there.
12. Gatekeeper: download the zip through a browser (quarantine flag), then
follow README-macos.txt → one-time Open Anyway, then normal launches.
13. On an Intel Mac: the same bundle runs (universal, both sharp slices).
14. Optional: notarized build → double-click installs with no warning,
`spctl -a -vv -t exec Luminary.app` says `accepted`.
## Known limits
- **No Dock menu.** The launcher exits once the browser opens; stopping is
`--stop` / `Stop Luminary.command`, not a Quit menu item.
- **Ad-hoc signing is per-bundle.** Copying the app with an archiver that drops
extended attributes can make macOS call it damaged; the zip is made with
`ditto` for that reason.
- **Universal builds install sharp twice** (one `npm ci` per architecture) and
copy the second slice's `@img` packages across; this is tested for layout, not
for runtime, until both architectures are exercised.
- **Icon quality depends on the source.** `public/logo.png` is 147×160, so the
generated `.icns` is soft; pass `--icon` with a 1024×1024 PNG for a release.
- **No auto-update, no file associations, no login item.** Same phase-2 list as
Windows.
+858
View File
@@ -0,0 +1,858 @@
#!/usr/bin/env node
/**
* Build the optional self-contained macOS app for Luminary.
*
* Like windows/build.mjs this is deliberately additive: it only reads the
* repository (`dist/`, `server/`, `package.json`) and writes everything into a
* directory outside the checkout. Nothing in `src/`, `server/`, `package.json`,
* the Dockerfile or the deploy script is modified, and no npm script is added.
* Run it directly, on macOS:
*
* node macos/build.mjs # host arch, Node 24, ad-hoc signed
* node macos/build.mjs --arch universal --dmg
* node macos/build.mjs --node v22.23.5 # minimum macOS 11.0
* node macos/build.mjs --skip-build --sign none
*
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
* the parent of `server/`), with a native shim as the app's main executable:
*
* Luminary.app/Contents/
* Info.plist, PkgInfo
* MacOS/Luminary native shim that execs the launcher script
* Resources/
* launcher.sh start/stop/status/verify logic (bash)
* Luminary.icns
* version.txt, README-macos.txt
* runtime/node official Node for this architecture
* app/ unchanged server/, dist/, production deps
*/
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import {
chmodSync,
cpSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
renameSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const LAUNCHER_DIR = path.join(HERE, 'launcher');
const RELEASES_DIR = path.join(HERE, 'releases');
const DEFAULT_NODE = 'v24.22.2';
const DEFAULT_BUNDLE_ID = 'net.maple-street.luminary';
const INFO_PLIST = path.join(HERE, 'Info.plist');
const ENTITLEMENTS = path.join(HERE, 'entitlements.plist');
const HELP = `Luminary macOS app
Usage: node macos/build.mjs [options]
--out <dir> output directory (default: ~/Library/Caches/luminary-macos).
Must be outside this repository; the app is staged in
<out>/stage/Luminary.app and archived next to it.
--skip-build reuse the existing dist/ instead of running npm run build
--node <version> bundled Node version (default ${DEFAULT_NODE}).
v22.18+ gives a macOS 11.0 bundle; v24+ needs macOS 13.5.
--node-bin <path> bundle this node binary instead of downloading one
--arch <arch> host (default), arm64, x64 or universal
--target <ver> minimum macOS version (default: derived from Node;
e.g. 11.0 for Node 22, 13.5 for Node 24)
--sign <kind> adhoc (default), developer-id or none
--identity <name> Developer ID Application identity for --sign developer-id
--notarize <name> notarytool keychain profile; implies --sign developer-id
--dmg also write a disk image (default)
--no-dmg skip the disk image
--icon <png> icon source (default: macos/icon-1024.png)
--bundle-id <id> CFBundleIdentifier (default ${DEFAULT_BUNDLE_ID})
--allow-dirty skip the check that the checkout is clean outside macos/
--publish copy the finished zip and dmg to macos/releases
--help print this text
Requires macOS with the Xcode command line tools (clang, codesign, ditto,
hdiutil, sips, iconutil). Nothing is written into the repository except with
--publish.
`;
function fail(message) {
process.stderr.write(`macos: FAILED: ${message}\n`);
process.exit(1);
}
function log(step, message) {
process.stdout.write(`macos: ${step.padEnd(9)} ${message}\n`);
}
function warn(message) {
process.stderr.write(`macos: warning: ${message}\n`);
}
function capture(command, args, cwd) {
return spawnSync(command, args, { cwd, encoding: 'utf8' });
}
function run(command, args, cwd, extraEnv) {
log('run', [command, ...args].join(' '));
const result = spawnSync(command, args, {
cwd,
stdio: 'inherit',
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
});
if (result.error) fail(`${command} could not start: ${result.error.message}`);
if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`);
return result;
}
function defaultOutDir() {
return path.join(os.homedir(), 'Library', 'Caches', 'luminary-macos');
}
function parseArgs(argv) {
const options = {
out: defaultOutDir(),
node: DEFAULT_NODE,
nodeBin: '',
arch: 'host',
target: '',
sign: 'adhoc',
identity: '',
notarize: '',
dmg: true,
build: true,
icon: path.join(HERE, 'icon-1024.png'),
bundleId: DEFAULT_BUNDLE_ID,
allowDirty: false,
publish: false,
help: false,
};
const value = (index, flag) => {
const next = argv[index + 1];
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
return next;
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--out') {
options.out = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--node') {
const version = value(i, arg);
options.node = version.startsWith('v') ? version : `v${version}`;
i += 1;
} else if (arg === '--node-bin') {
options.nodeBin = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--arch') {
options.arch = value(i, arg);
i += 1;
} else if (arg === '--target') {
options.target = value(i, arg);
i += 1;
} else if (arg === '--sign') {
options.sign = value(i, arg);
i += 1;
} else if (arg === '--identity') {
options.identity = value(i, arg);
i += 1;
} else if (arg === '--notarize') {
options.notarize = value(i, arg);
i += 1;
} else if (arg === '--icon') {
options.icon = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--bundle-id') {
options.bundleId = value(i, arg);
i += 1;
} else if (arg === '--skip-build') {
options.build = false;
} else if (arg === '--dmg') {
options.dmg = true;
} else if (arg === '--no-dmg') {
options.dmg = false;
} else if (arg === '--allow-dirty') {
options.allowDirty = true;
} else if (arg === '--publish') {
options.publish = true;
} else if (arg === '--help' || arg === '-h') {
options.help = true;
} else {
fail(`unknown option ${arg} (see --help)`);
}
}
if (!['host', 'arm64', 'x64', 'universal'].includes(options.arch)) {
fail(`--arch must be host, arm64, x64 or universal (got ${options.arch})`);
}
if (!['adhoc', 'developer-id', 'none'].includes(options.sign)) {
fail(`--sign must be adhoc, developer-id or none (got ${options.sign})`);
}
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
fail(`--node must look like v24.22.2 (got ${options.node})`);
}
if (options.notarize) options.sign = 'developer-id';
if (options.sign === 'developer-id' && !options.identity) {
fail('--sign developer-id needs --identity "Developer ID Application: ..."');
}
if (options.nodeBin && !existsSync(options.nodeBin)) {
fail(`--node-bin not found: ${options.nodeBin}`);
}
return options;
}
/**
* The staged app and its runtime must not land in the checkout: scripts/deploy
* rsyncs the worktree to production and docker build would pull it into the
* context.
*/
function assertOutsideRepo(outDir) {
const relative = path.relative(ROOT, outDir);
const inside = !relative.startsWith('..') && !path.isAbsolute(relative);
if (inside) {
fail(
`--out resolves inside the repository (${outDir}).\n` +
'Pick a directory outside the checkout, or omit --out to use the cache.',
);
}
}
function git(args, { trim = true } = {}) {
const result = capture('git', args, ROOT);
if (result.error || result.status !== 0) return null;
return trim ? result.stdout.trim() : result.stdout;
}
/** Only this folder and the long-standing untracked logo may be dirty. */
function checkRepoClean(options) {
const status = git(['status', '--porcelain'], { trim: false });
if (status === null) {
warn('git is unavailable here; skipping the worktree check');
return;
}
const unexpected = status
.split('\n')
.filter((line) => line.length > 3)
.map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim())
.filter((file) => file && !file.startsWith('macos/') && file !== 'logo.png');
if (!unexpected.length) return;
if (options.allowDirty) {
warn(`building from a modified checkout: ${unexpected.join(', ')}`);
return;
}
fail(
`the checkout has changes outside macos/:\n ${unexpected.join('\n ')}\n` +
'Commit or stash them, or pass --allow-dirty to build anyway.',
);
}
function readPackage() {
const file = path.join(ROOT, 'package.json');
if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)');
return JSON.parse(readFileSync(file, 'utf8'));
}
function sha256File(file) {
return createHash('sha256').update(readFileSync(file)).digest('hex');
}
async function download(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`);
return Buffer.from(await response.arrayBuffer());
}
function fileType(file) {
const result = capture('file', ['-b', file]);
return result.status === 0 ? result.stdout.trim() : '';
}
function nodeMajor(version) {
return Number(version.slice(1).split('.')[0]);
}
function minimumOS(version) {
const major = nodeMajor(version);
if (major === 22) return '11.0';
if (major >= 24) return '13.5';
return '11.0';
}
function resolveArchs(requested) {
if (requested === 'universal') return ['arm64', 'x64'];
if (requested === 'host') return [process.arch === 'arm64' ? 'arm64' : 'x64'];
return [requested];
}
function clangArch(arch) {
return arch === 'x64' ? 'x86_64' : 'arm64';
}
function ensureUi(options) {
const dist = path.join(ROOT, 'dist', 'index.html');
if (options.build) {
log('ui', 'npm run build (typecheck + vite build + compressed variants)');
run('npm', ['run', 'build'], ROOT);
} else {
log('ui', 'reusing the existing dist/ (--skip-build)');
}
if (!existsSync(dist)) fail('dist/index.html is missing; drop --skip-build or run "npm run build"');
}
function copyServer(appDir) {
cpSync(path.join(ROOT, 'server'), path.join(appDir, 'server'), {
recursive: true,
filter: (source) => {
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
if (relative === 'data' || relative.startsWith('data/')) return false;
if (/\.test\.(mjs|ts)$/.test(relative)) return false;
return true;
},
});
}
function copyLegal(appDir) {
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
const source = path.join(ROOT, name);
if (existsSync(source)) cpSync(source, path.join(appDir, name));
}
const licenses = path.join(ROOT, 'licenses');
if (existsSync(licenses)) cpSync(licenses, path.join(appDir, 'licenses'), { recursive: true });
}
function installDeps(appDir, archs, outDir) {
cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json'));
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
log('deps', `npm ci --omit=dev --os=darwin --cpu=${archs[0]} (sharp darwin-${archs[0]})`);
// sharp resolves its prebuilt binary through optionalDependencies, so npm can
// fetch the target architecture's package from any host. The ONNX skip keeps
// the postinstall from downloading the CUDA build; CPU binaries ship in the
// package.
run(
'npm',
['ci', '--omit=dev', '--os=darwin', `--cpu=${archs[0]}`, '--ignore-scripts', '--no-audit', '--no-fund'],
appDir,
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
);
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
// A universal app needs both sharp slices; npm's --cpu selects one at a time,
// so install the second architecture separately and copy its packages across.
for (const arch of archs.slice(1)) {
const side = path.join(outDir, `deps-${arch}`);
rmSync(side, { recursive: true, force: true });
mkdirSync(side, { recursive: true });
cpSync(path.join(ROOT, 'package.json'), path.join(side, 'package.json'));
cpSync(path.join(ROOT, 'package-lock.json'), path.join(side, 'package-lock.json'));
run(
'npm',
['ci', '--omit=dev', '--os=darwin', `--cpu=${arch}`, '--ignore-scripts', '--no-audit', '--no-fund'],
side,
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
);
for (const pkg of [`@img/sharp-darwin-${arch}`, `@img/sharp-libvips-darwin-${arch}`]) {
const from = path.join(side, 'node_modules', pkg);
if (!existsSync(from)) fail(`${pkg} was not installed for the ${arch} slice`);
rmSync(path.join(appDir, 'node_modules', pkg), { recursive: true, force: true });
cpSync(from, path.join(appDir, 'node_modules', pkg), { recursive: true });
log('deps', `added ${pkg}`);
}
rmSync(side, { recursive: true, force: true });
}
verifySharp(appDir, archs);
}
function verifySharp(appDir, archs) {
for (const arch of archs) {
const dir = path.join(appDir, 'node_modules', '@img', `sharp-darwin-${arch}`);
if (!existsSync(dir)) {
warn(`@img/sharp-darwin-${arch} is missing; the server will fall back to JPEG proxies`);
continue;
}
const binaries = [];
const walk = (current) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) walk(absolute);
else if (/\.(node|dylib)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
}
};
walk(dir);
const libvips = path.join(appDir, 'node_modules', '@img', `sharp-libvips-darwin-${arch}`);
log(
'deps',
binaries.some((file) => file.endsWith('.node'))
? `sharp darwin-${arch} ready (${binaries.length} native file(s)${existsSync(libvips) ? ', libvips included' : ''})`
: `sharp darwin-${arch} has no .node binary`,
);
}
}
async function ensureNode(options, outDir, archs) {
if (options.nodeBin) {
const kind = fileType(options.nodeBin);
if (!/Mach-O/.test(kind)) fail(`--node-bin is not a Mach-O binary (${kind || 'unknown'})`);
const binaryArch = /universal/.test(kind) ? 'universal' : /arm64/.test(kind) ? 'arm64' : 'x64';
if (binaryArch !== 'universal' && (archs.length > 1 || binaryArch !== archs[0])) {
fail(
`--node-bin is ${binaryArch} but --arch needs ${archs.join(' + ')}.\n` +
'Use the official nodejs.org tarball, or omit --node-bin to download both slices.',
);
}
log('node', `using ${options.nodeBin} (${binaryArch})`);
return { path: options.nodeBin, arch: binaryArch, version: options.node, hash: sha256File(options.nodeBin) };
}
const version = options.node;
const major = nodeMajor(version);
if (major === 23) fail('Node 23 is not an LTS line; use v22 (macOS 11) or v24 (macOS 13.5)');
if (major < 22) fail(`Node ${version} is too old: node:sqlite needs 22.13+ (type stripping 22.18+)`);
if (major === 22 && Number(version.split('.')[1]) < 18) {
fail(`${version} cannot strip types by default; server/denoise-worker.mjs needs v22.18+`);
}
const cache = path.join(outDir, 'cache', `node-${version}`);
mkdirSync(cache, { recursive: true });
const sumsFile = path.join(cache, 'SHASUMS256.txt');
if (!existsSync(sumsFile)) {
log('node', `downloading SHASUMS256.txt for ${version}`);
writeFileSync(sumsFile, await download(`https://nodejs.org/dist/${version}/SHASUMS256.txt`));
}
const sums = new Map(
readFileSync(sumsFile, 'utf8')
.split('\n')
.filter(Boolean)
.map((line) => {
const [hash, name] = line.trim().split(/\s+/);
return [name, hash];
}),
);
const binaries = [];
for (const arch of archs) {
const name = `node-${version}-darwin-${arch}.tar.gz`;
const tarball = path.join(cache, name);
if (!existsSync(tarball)) {
log('node', `downloading ${name}`);
try {
writeFileSync(tarball, await download(`https://nodejs.org/dist/${version}/${name}`));
} catch (error) {
fail(`could not download ${name}: ${error.message}`);
}
}
const hash = sha256File(tarball);
const expected = sums.get(name);
if (expected && expected !== hash) {
rmSync(tarball, { force: true });
fail(`${name} failed its SHA-256 check (${hash} != ${expected}); re-run to download again`);
}
if (!expected) warn(`${name} has no published checksum; using it unverified`);
const dir = path.join(cache, `node-${version}-darwin-${arch}`);
const binary = path.join(dir, 'bin', 'node');
if (!existsSync(binary)) {
mkdirSync(dir, { recursive: true });
run('tar', ['-xzf', tarball, '-C', dir, '--strip-components=1']);
}
const kind = fileType(binary);
if (!/Mach-O/.test(kind)) fail(`extracted ${arch} node is not a Mach-O binary (${kind})`);
binaries.push(binary);
log('node', `${version} darwin-${arch} verified (sha256 ${hash.slice(0, 12)}…)`);
}
if (binaries.length === 1) {
return { path: binaries[0], arch: archs[0], version, hash: sha256File(binaries[0]) };
}
const universal = path.join(cache, `node-${version}-universal`);
rmSync(universal, { force: true });
run('lipo', ['-create', ...binaries, '-output', universal]);
const kind = fileType(universal);
if (!/universal binary/.test(kind)) fail(`lipo did not produce a universal binary (${kind})`);
chmodSync(universal, 0o755);
log('node', `${version} universal (arm64 + x86_64)`);
return { path: universal, arch: 'universal', version, hash: sha256File(universal) };
}
function checkNodePortability(binary) {
const result = capture('otool', ['-L', binary]);
if (result.status !== 0) return;
const foreign = result.stdout
.split('\n')
.slice(1)
.map((line) => line.trim().split(' ')[0])
.filter((lib) => lib && !lib.startsWith('/usr/lib/') && !lib.startsWith('/System/'));
if (foreign.length) {
warn(
`the bundled node links to libraries outside macOS: ${foreign.join(', ')}.\n` +
'Use the official nodejs.org tarball so the app runs on a Mac without Homebrew.',
);
}
}
function compileShim(app, archs, target) {
const found = capture('xcrun', ['--find', 'clang']);
const clang = found.status === 0 ? found.stdout.trim() : '';
if (!clang) {
fail(
'clang is missing. Install the Xcode command line tools:\n' +
' xcode-select --install\n' +
'and run the build again.',
);
}
const output = path.join(app, 'Contents', 'MacOS', 'Luminary');
const args = ['-O2', '-Wall', '-Wextra', `-mmacosx-version-min=${target}`];
for (const arch of archs) args.push('-arch', clangArch(arch));
args.push('-o', output, path.join(LAUNCHER_DIR, 'main.c'));
run(clang, args);
chmodSync(output, 0o755);
log('launcher', `native shim (${archs.join(' + ')}, macOS ${target}+)`);
}
function renderInfoPlist(app, { version, target, bundleId }) {
const text = readFileSync(INFO_PLIST, 'utf8')
.replaceAll('__VERSION__', version)
.replaceAll('__MIN_OS__', target)
.replaceAll('__BUNDLE_ID__', bundleId);
writeFileSync(path.join(app, 'Contents', 'Info.plist'), text);
writeFileSync(path.join(app, 'Contents', 'PkgInfo'), 'APPL????');
}
function buildIcon(app, source, outDir) {
if (!existsSync(source)) {
warn(`icon source not found: ${source}; the app will use the generic icon`);
return;
}
const sips = '/usr/bin/sips';
const iconutil = '/usr/bin/iconutil';
if (!existsSync(sips) || !existsSync(iconutil)) {
warn('sips/iconutil are missing; skipping the icon');
return;
}
const probe = capture(sips, ['-g', 'pixelWidth', '-g', 'pixelHeight', source]);
const width = Number((probe.stdout.match(/pixelWidth:\s*(\d+)/) ?? [])[1] ?? 0);
const height = Number((probe.stdout.match(/pixelHeight:\s*(\d+)/) ?? [])[1] ?? 0);
if (!width || !height) {
warn(`could not read the icon size of ${source}; skipping the icon`);
return;
}
const square = Math.max(width, height);
if (square < 512) {
warn(
`the icon source is ${width}x${height}; the .icns will look soft.\n` +
'Pass --icon with a 1024x1024 PNG for a crisp Dock icon.',
);
}
const work = path.join(outDir, 'cache', 'icon');
rmSync(work, { recursive: true, force: true });
mkdirSync(path.join(work, 'Luminary.iconset'), { recursive: true });
const padded = path.join(work, 'square.png');
if (width === height) {
cpSync(source, padded);
} else {
run(sips, ['-p', String(square), String(square), '--padColor', '0B0D10', source, '--out', padded]);
}
const iconset = path.join(work, 'Luminary.iconset');
for (const size of [16, 32, 128, 256, 512]) {
for (const scale of [1, 2]) {
const pixels = size * scale;
const name = scale === 1 ? `icon_${size}x${size}.png` : `icon_${size}x${size}@2x.png`;
run(sips, ['-z', String(pixels), String(pixels), padded, '--out', path.join(iconset, name)]);
}
}
run(iconutil, ['-c', 'icns', iconset, '-o', path.join(app, 'Contents', 'Resources', 'Luminary.icns')]);
log('icon', `Luminary.icns from ${path.relative(ROOT, source)} (${width}x${height})`);
}
function writeVersion(resources, info) {
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
const lines = [
`Luminary ${info.version}`,
`commit ${commit}`,
`built ${new Date().toISOString()}`,
`node ${info.nodeVersion} darwin-${info.nodeArch} sha256 ${info.nodeHash} size ${info.nodeSize}`,
`arch ${info.archs.join(' + ')}`,
`minimum macOS ${info.target}`,
'launcher native shim -> launcher.sh',
];
writeFileSync(path.join(resources, 'version.txt'), `${lines.join('\n')}\n`);
return commit;
}
function machOFiles(root) {
const found = [];
const walk = (current) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) {
walk(absolute);
continue;
}
if (!entry.isFile()) continue;
// `file` per file would be hundreds of subprocesses across node_modules;
// only native modules, dylibs and executables can be Mach-O here.
const stat = statSync(absolute);
const candidate =
/\.(node|dylib|so)$/i.test(entry.name) || (stat.mode & 0o111) !== 0;
if (candidate && /Mach-O/.test(fileType(absolute))) found.push(absolute);
}
};
walk(root);
return found;
}
function signApp(app, options) {
if (options.sign === 'none') {
warn(
'the app is unsigned: arm64 Macs refuse to launch it at all, and Intel\n' +
'Macs show the Gatekeeper warning. Ship adhoc or developer-id instead.',
);
return;
}
const nested = machOFiles(app).filter((file) => !file.endsWith('/Contents/MacOS/Luminary'));
for (const file of nested) {
if (options.sign === 'adhoc') {
run('codesign', ['--force', '--sign', '-', file]);
continue;
}
const kind = fileType(file);
const executable = /executable/.test(kind) && !/dylib|bundle/.test(kind);
const args = ['--force', '--timestamp', '--sign', options.identity];
if (executable) args.push('--options', 'runtime', '--entitlements', ENTITLEMENTS);
args.push(file);
run('codesign', args);
}
const finalArgs =
options.sign === 'adhoc'
? ['--force', '--sign', '-', app]
: [
'--force',
'--timestamp',
'--options',
'runtime',
'--entitlements',
ENTITLEMENTS,
'--sign',
options.identity,
app,
];
run('codesign', finalArgs);
const verify = capture('codesign', ['--verify', '--deep', '--strict', '--verbose=2', app]);
if (verify.status !== 0) fail(`codesign verification failed:\n${verify.stderr.trim()}`);
log('sign', options.sign === 'adhoc' ? 'ad-hoc signature verified' : `signed with ${options.identity}`);
}
function zipApp(app, zipPath) {
rmSync(zipPath, { force: true });
// ditto keeps symlinks, extended attributes and the code signature intact;
// `zip -r` corrupts bundles often enough to produce "app is damaged".
run('ditto', ['-c', '-k', '--keepParent', '--sequesterRsrc', app, zipPath]);
return statSync(zipPath).size;
}
function makeDmg(app, dmgPath, outDir) {
const root = path.join(outDir, 'dmg');
rmSync(root, { recursive: true, force: true });
mkdirSync(root, { recursive: true });
cpSync(app, path.join(root, 'Luminary.app'), { recursive: true, verbatimSymlinks: true });
symlinkSync('Applications', path.join(root, 'Applications'));
cpSync(path.join(HERE, 'README-macos.txt'), path.join(root, 'README-macos.txt'));
const stop = path.join(LAUNCHER_DIR, 'Stop Luminary.command');
if (existsSync(stop)) {
cpSync(stop, path.join(root, 'Stop Luminary.command'));
chmodSync(path.join(root, 'Stop Luminary.command'), 0o755);
}
rmSync(dmgPath, { force: true });
run('hdiutil', [
'create',
'-volname',
'Luminary',
'-srcfolder',
root,
'-ov',
'-format',
'UDZO',
dmgPath,
]);
rmSync(root, { recursive: true, force: true });
return statSync(dmgPath).size;
}
function notarize(artifact, profile) {
log('notarize', `submitting ${path.basename(artifact)}`);
run('xcrun', ['notarytool', 'submit', artifact, '--keychain-profile', profile, '--wait']);
}
function staple(artifact) {
run('xcrun', ['stapler', 'staple', artifact]);
run('xcrun', ['stapler', 'validate', artifact]);
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
process.stdout.write(HELP);
return 0;
}
if (process.platform !== 'darwin') {
fail(
'the macOS app must be built on macOS: it needs clang, codesign, ditto and hdiutil.\n' +
'The Windows bundle is the one that cross-builds from Linux.',
);
}
assertOutsideRepo(options.out);
const pkg = readPackage();
const archs = resolveArchs(options.arch);
const target = options.target || minimumOS(options.node);
const [targetMajor, targetMinor = 0] = target.split('.').map(Number);
if (nodeMajor(options.node) >= 24 && (targetMajor < 13 || (targetMajor === 13 && targetMinor < 5))) {
fail(
`Node ${options.node} needs macOS 13.5 or newer, but --target is ${target}.\n` +
'Build with --node v22.23.5 for a macOS 11.0 bundle.',
);
}
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
log('out', options.out);
checkRepoClean(options);
ensureUi(options);
const stageRoot = path.join(options.out, 'stage');
const workRoot = path.join(options.out, 'stage.next');
const app = path.join(workRoot, 'Luminary.app');
const contents = path.join(app, 'Contents');
const resources = path.join(contents, 'Resources');
const appDir = path.join(resources, 'app');
rmSync(workRoot, { recursive: true, force: true });
for (const dir of [path.join(contents, 'MacOS'), resources, appDir, path.join(resources, 'runtime')]) {
mkdirSync(dir, { recursive: true });
}
log('stage', 'copying dist/ and server/ (the layout the server expects)');
cpSync(path.join(ROOT, 'dist'), path.join(appDir, 'dist'), { recursive: true });
copyServer(appDir);
copyLegal(appDir);
installDeps(appDir, archs, options.out);
const node = await ensureNode(options, options.out, archs);
checkNodePortability(node.path);
cpSync(node.path, path.join(resources, 'runtime', 'node'));
chmodSync(path.join(resources, 'runtime', 'node'), 0o755);
log('node', `bundled ${path.basename(node.path)} (${(statSync(node.path).size / 1024 / 1024).toFixed(1)} MB)`);
cpSync(path.join(LAUNCHER_DIR, 'launcher.sh'), path.join(resources, 'launcher.sh'));
chmodSync(path.join(resources, 'launcher.sh'), 0o755);
cpSync(path.join(HERE, 'README-macos.txt'), path.join(resources, 'README-macos.txt'));
renderInfoPlist(app, { version: pkg.version, target, bundleId: options.bundleId });
compileShim(app, archs, target);
buildIcon(app, options.icon, options.out);
const commit = writeVersion(resources, {
version: pkg.version,
nodeVersion: options.node,
nodeArch: node.arch,
nodeHash: node.hash,
nodeSize: statSync(node.path).size,
archs,
target,
});
signApp(app, options);
const label = archs.length > 1 ? 'universal' : archs[0];
const zipPath = path.join(options.out, `Luminary-${pkg.version}-mac-${label}.zip`);
let zipBytes = zipApp(app, zipPath);
if (options.notarize) {
notarize(zipPath, options.notarize);
staple(app);
zipBytes = zipApp(app, zipPath);
} else {
const assessment = capture('spctl', ['-a', '-vv', '-t', 'exec', app]);
if (assessment.status !== 0) {
log('gatekeeper', 'not notarized: users must use Privacy & Security > Open Anyway');
}
}
let dmgPath = '';
let dmgBytes = 0;
if (options.dmg) {
dmgPath = path.join(options.out, `Luminary-${pkg.version}-mac-${label}.dmg`);
dmgBytes = makeDmg(app, dmgPath, options.out);
if (options.notarize) {
notarize(dmgPath, options.notarize);
staple(dmgPath);
}
log('dmg', `${path.basename(dmgPath)} (${(dmgBytes / 1024 / 1024).toFixed(1)} MB)`);
}
// The isolation contract: nothing outside macos/ may have changed. Checked
// before --publish writes anything into the checkout.
if (!options.allowDirty) checkRepoClean(options);
rmSync(stageRoot, { recursive: true, force: true });
renameSync(workRoot, stageRoot);
let published = [];
if (options.publish) {
mkdirSync(RELEASES_DIR, { recursive: true });
const sums = [];
for (const artifact of [zipPath, ...(dmgPath ? [dmgPath] : [])]) {
const targetPath = path.join(RELEASES_DIR, path.basename(artifact));
cpSync(artifact, targetPath);
sums.push(`${sha256File(targetPath)} ${path.basename(targetPath)}`);
log('publish', path.relative(ROOT, targetPath));
}
writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`);
published = sums;
}
process.stdout.write(
[
'',
'macos build PASSED',
` app ${path.join(stageRoot, 'Luminary.app')}`,
` zip ${zipPath}`,
` zip size ${(zipBytes / 1024 / 1024).toFixed(1)} MB`,
` zip sha256 ${sha256File(zipPath)}`,
...(dmgPath
? [
` dmg ${dmgPath}`,
` dmg size ${(dmgBytes / 1024 / 1024).toFixed(1)} MB`,
` dmg sha256 ${sha256File(dmgPath)}`,
]
: []),
` arch ${label}`,
` node ${options.node} darwin-${node.arch}`,
` target macOS ${target}+`,
` signature ${options.sign}${options.identity ? ` (${options.identity})` : ''}`,
` commit ${commit}`,
...(published.length ? ['', ...published.map((line) => ` publish ${line}`)] : []),
'',
options.notarize
? 'Notarized and stapled: users can open it with a normal double-click.'
: 'Not notarized: first launch needs Privacy & Security > Open Anyway (see README-macos.txt).',
'',
].join('\n'),
);
return 0;
}
main().then(
(code) => {
process.exitCode = code;
},
(error) => {
fail(error instanceof Error ? error.message : String(error));
},
);
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- V8 compiles JavaScript at run time; the hardened runtime blocks that
unless the process opts in. Node's own documentation names these two. -->
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<!-- sharp loads libvips as a dylib from its own package directory; library
validation would otherwise reject it when the signatures differ. -->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
Binary file not shown.

After

Width:  |  Height:  |  Size: 363 KiB

+35
View File
@@ -0,0 +1,35 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<defs>
<linearGradient id="tile" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#141b25"/>
<stop offset="1" stop-color="#07090c"/>
</linearGradient>
<radialGradient id="glow" cx="50%" cy="36%" r="64%">
<stop offset="0" stop-color="#2f6cb5" stop-opacity="0.5"/>
<stop offset="0.65" stop-color="#123055" stop-opacity="0.16"/>
<stop offset="1" stop-color="#0b0d10" stop-opacity="0"/>
</radialGradient>
<linearGradient id="bar" x1="0" y1="0" x2="0.35" y2="1">
<stop offset="0" stop-color="#a6d2ff"/>
<stop offset="0.18" stop-color="#6cb0fb"/>
<stop offset="0.38" stop-color="#3d8df0"/>
<stop offset="0.58" stop-color="#14509f"/>
<stop offset="0.78" stop-color="#0a3272"/>
<stop offset="1" stop-color="#021f4c"/>
</linearGradient>
<clipPath id="tileClip">
<rect x="100" y="100" width="824" height="824" rx="185"/>
</clipPath>
</defs>
<g clip-path="url(#tileClip)">
<rect x="100" y="100" width="824" height="824" fill="url(#tile)"/>
<rect x="100" y="100" width="824" height="824" fill="url(#glow)"/>
</g>
<rect x="100.5" y="100.5" width="823" height="823" rx="184.5" fill="none" stroke="#ffffff" stroke-opacity="0.10" stroke-width="1"/>
<g transform="translate(206 178) scale(4.2)">
<path d="M 0 127 Q 0 134 7 134 L 26 134 Q 33 134 33 127 L 33 112.5 A 16.5 16.5 0 0 0 0 112.5 Z" fill="url(#bar)"/>
<path d="M 37 127 Q 37 134 44 134 L 62 134 Q 69 134 69 127 L 69 79 A 16 16 0 0 0 37 79 Z" fill="url(#bar)"/>
<path d="M 74 126.5 Q 74 133.5 81 133.5 L 99 133.5 Q 106 133.5 106 126.5 L 106 41 A 16 16 0 0 0 74 41 Z" fill="url(#bar)"/>
<path d="M 110 126 Q 110 133 117 133 L 134 133 Q 141 133 141 126 L 141 93.5 A 15.5 15.5 0 0 0 110 93.5 Z" fill="url(#bar)"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
# Stop the Luminary local engine started by Luminary.app.
# Double-clicking a .command file opens Terminal for as long as this runs.
set -u
APP="/Applications/Luminary.app"
if [ ! -d "$APP" ]; then
APP="$(cd "$(dirname "$0")" && pwd)/Luminary.app"
fi
if [ ! -d "$APP" ]; then
echo "Luminary.app was not found in /Applications. Move it there and try again."
read -r -p "Press Return to close this window." _
exit 1
fi
"$APP/Contents/Resources/launcher.sh" --stop
read -r -p "Press Return to close this window." _
+252
View File
@@ -0,0 +1,252 @@
#!/bin/bash
# Luminary.app launcher.
#
# Called by the native shim in Contents/MacOS/Luminary. Keeps the same rules as
# the Windows launcher: pick a loopback port, start the bundled node exactly like
# `node server/index.mjs`, wait for /api/health, then open the browser. The
# server is detached and keeps running after the app exits, so launching again
# reuses it instead of starting a second copy.
#
# launcher.sh start (or reuse) and open the window
# launcher.sh --stop stop the server recorded in runtime.json
# launcher.sh --status print pid, port, health and data directory
# launcher.sh --verify check that this is a complete bundle (exit 3 if not)
# launcher.sh --browser open a normal browser tab instead of an app window
set -u
HERE="$(cd "$(dirname "$0")" && pwd)"
APP="$HERE/app"
NODE="$HERE/runtime/node"
DATA="${LUMINARY_DATA:-$HOME/Library/Application Support/Luminary/data}"
STATE="$DATA/runtime.json"
LOGS="$DATA/logs"
WINDOW="${LUMINARY_WINDOW:-app}"
say() { printf 'Luminary: %s\n' "$*"; }
err() { printf 'Luminary: %s\n' "$*" >&2; }
die() { err "$*"; exit 1; }
# A blocking dialog for launches from Finder, where stderr goes nowhere.
dialog() {
local message
message=$(printf '%s' "$1" | tr '"' "'" | tr '\n' ' ')
if command -v osascript >/dev/null 2>&1; then
osascript -e "display dialog \"$message\" with title \"Luminary\" buttons {\"OK\"} default button 1 with icon caution" >/dev/null 2>&1 || true
fi
}
version_line() {
if [ -f "$HERE/version.txt" ]; then head -1 "$HERE/version.txt"; else echo "Luminary (version unknown)"; fi
}
state_port() {
[ -f "$STATE" ] || return 0
sed -n 's/.*"port"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$STATE" | head -1
}
state_pid() {
[ -f "$STATE" ] || return 0
sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$STATE" | head -1
}
# --noproxy forces a direct connection: offline, curl would otherwise resolve
# the system proxy/PAC first and every health probe would fail.
healthy() {
curl -fs -m 2 --noproxy '*' "http://127.0.0.1:$1/api/health" >/dev/null 2>&1
}
# Ask node rather than nc: the bundle always has one, and nc's flags differ
# between the BSD tool macOS ships and builds found elsewhere.
port_in_use() {
"$NODE" -e 'const net=require("net");const s=net.connect(+process.argv[1],"127.0.0.1");s.on("connect",()=>{s.destroy();process.exit(0)});s.on("error",()=>process.exit(1))' "$1" >/dev/null 2>&1
}
tail_logs() {
[ -f "$LOGS/server.err.log" ] || return 0
err "last lines from $LOGS/server.err.log:"
tail -n 20 "$LOGS/server.err.log" >&2 || true
}
open_window() {
local url="$1"
if [ "$WINDOW" = "browser" ]; then
open "$url"
return
fi
if [ -d "/Applications/Google Chrome.app" ] || [ -d "$HOME/Applications/Google Chrome.app" ]; then
open -na "Google Chrome" --args \
--app="$url" \
--user-data-dir="$DATA/window-profile-chrome" \
--window-size=1500,950 --no-first-run --no-default-browser-check \
--no-proxy-server
elif [ -d "/Applications/Microsoft Edge.app" ] || [ -d "$HOME/Applications/Microsoft Edge.app" ]; then
open -na "Microsoft Edge" --args \
--app="$url" \
--user-data-dir="$DATA/window-profile-edge" \
--window-size=1500,950 --no-first-run --no-default-browser-check \
--no-proxy-server
else
open "$url"
fi
}
verify() {
local status=0 file size
for file in "$NODE" "$APP/server/index.mjs" "$APP/dist/index.html"; do
if [ ! -f "$file" ]; then
err "missing: ${file#"$HERE"/}"
status=3
elif [ ! -s "$file" ]; then
err "empty: ${file#"$HERE"/}"
status=3
else
size=$(wc -c <"$file" | tr -d ' ')
say "ok: ${file#"$HERE"/} ($size bytes)"
fi
done
say "bundle: $HERE"
say "version: $(version_line)"
return $status
}
start() {
[ -x "$NODE" ] || chmod +x "$NODE" 2>/dev/null || true
if [ -f "$STATE" ]; then
local existing
existing=$(state_port)
if [ -n "$existing" ] && healthy "$existing"; then
say "already running on port $existing"
open_window "http://127.0.0.1:$existing"
exit 0
fi
rm -f "$STATE"
fi
if ! verify >/dev/null 2>&1; then
verify >&2 || true
dialog "This copy of Luminary is incomplete. Copy Luminary.app out of the disk image or zip and try again. If it still fails, download the app again."
exit 3
fi
mkdir -p "$DATA" "$LOGS" 2>/dev/null || {
dialog "Luminary cannot write to $DATA. Set LUMINARY_DATA to a folder you can write to and try again."
exit 1
}
local port=""
local candidate
# Brace expansion instead of seq: macOS does not ship seq.
for candidate in {8787..8887}; do
if ! port_in_use "$candidate"; then
port="$candidate"
break
fi
done
[ -n "$port" ] || { dialog "No free port between 8787 and 8887. Quit the app using one and try again."; exit 1; }
LUMINARY_DATA="$DATA" \
LUMINARY_LOCAL=1 \
HOST=127.0.0.1 \
PORT="$port" \
NODE_ENV=production \
nohup "$NODE" --disable-warning=ExperimentalWarning "$APP/server/index.mjs" \
>>"$LOGS/server.out.log" 2>>"$LOGS/server.err.log" &
local pid=$!
printf '{\n "pid": %s,\n "port": %s,\n "url": "http://127.0.0.1:%s",\n "data": "%s",\n "started": "%s"\n}\n' \
"$pid" "$port" "$port" "$DATA" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"$STATE"
local waited=0
while [ "$waited" -lt 240 ]; do
if healthy "$port"; then
open_window "http://127.0.0.1:$port"
exit 0
fi
if ! kill -0 "$pid" 2>/dev/null; then
rm -f "$STATE"
tail_logs
dialog "Luminary's local engine stopped while starting. Log: $LOGS/server.err.log"
exit 1
fi
sleep 0.5
waited=$((waited + 1))
done
kill "$pid" 2>/dev/null || true
rm -f "$STATE"
tail_logs
dialog "Luminary did not start within 120 seconds. Log: $LOGS/server.err.log"
exit 1
}
stop() {
if [ ! -f "$STATE" ]; then
say "not running"
return 0
fi
local pid
pid=$(state_pid)
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
kill -TERM "$pid" 2>/dev/null || true
local tick
for tick in {1..20}; do
kill -0 "$pid" 2>/dev/null || break
sleep 0.25
done
kill -0 "$pid" 2>/dev/null && kill -KILL "$pid" 2>/dev/null || true
say "stopped (pid $pid)"
else
say "not running (removed a stale runtime.json)"
fi
rm -f "$STATE"
}
status() {
local port pid
port=$(state_port)
pid=$(state_pid)
say "version: $(version_line)"
say "bundle: $HERE"
say "data: $DATA"
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
say "pid: $pid"
elif [ -n "$pid" ]; then
say "pid: $pid (not running)"
else
say "pid: -"
fi
if [ -n "$port" ] && healthy "$port"; then
say "health: ok on http://127.0.0.1:$port"
elif [ -n "$port" ]; then
say "health: no response on port $port"
else
say "health: not started"
fi
}
case "${1:-}" in
--stop) stop ;;
--status) status ;;
--verify) verify; exit $? ;;
--browser) WINDOW=browser; start ;;
--help | -h)
cat <<'USAGE'
Luminary.app launcher
No argument starts the app (or reuses a running copy) and opens the window.
--browser open a normal browser tab instead of a Chrome/Edge app window
--stop stop the local engine this bundle started
--status print version, pid, port, health and the data directory
--verify check that the bundle is complete
Data: ~/Library/Application Support/Luminary/data (override with LUMINARY_DATA)
Logs: <data>/logs/server.out.log and server.err.log
USAGE
;;
"") start ;;
*)
err "unknown argument: $1 (try --help)"
exit 2
;;
esac
+73
View File
@@ -0,0 +1,73 @@
/*
* Luminary.app main executable.
*
* The bundle needs a Mach-O main executable so it can be code signed and, if a
* certificate is ever bought, notarized: Apple's notary service rejects a
* bundle whose CFBundleExecutable is a shell script. This shim resolves its own
* path, finds Contents/Resources/launcher.sh next to it, and execs bash on it,
* passing every argument through. All the actual launcher logic lives in that
* script, where it can be changed without recompiling anything.
*/
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
/** Write this process's executable path into buf, or return -1. */
static int executable_path(char *buf, size_t size) {
#ifdef __APPLE__
uint32_t needed = (uint32_t)size;
if (_NSGetExecutablePath(buf, &needed) != 0) return -1;
return 0;
#else
/* Not used in the bundle; kept so the shim can be built and tested when
* packaging is exercised from a non-Apple host. */
ssize_t length = readlink("/proc/self/exe", buf, size - 1);
if (length < 0) return -1;
buf[length] = '\0';
return 0;
#endif
}
int main(int argc, char **argv) {
char raw[PATH_MAX];
char exe[PATH_MAX];
char script[PATH_MAX];
if (executable_path(raw, sizeof raw) != 0) {
fprintf(stderr, "luminary: cannot resolve the application path\n");
return 1;
}
if (realpath(raw, exe) == NULL) {
fprintf(stderr, "luminary: cannot resolve %s\n", raw);
return 1;
}
/* exe is .../Luminary.app/Contents/MacOS/Luminary */
char *slash = strrchr(exe, '/');
if (slash == NULL) {
fprintf(stderr, "luminary: unexpected executable path %s\n", exe);
return 1;
}
*slash = '\0';
if (snprintf(script, sizeof script, "%s/../Resources/launcher.sh", exe) >= (int)sizeof script) {
fprintf(stderr, "luminary: application path is too long\n");
return 1;
}
char *args[argc + 2];
args[0] = "/bin/bash";
args[1] = script;
for (int i = 1; i < argc; i++) args[i + 1] = argv[i];
args[argc + 1] = NULL;
execv("/bin/bash", args);
perror("luminary: could not start the launcher");
return 1;
}
+286 -89
View File
@@ -1,17 +1,19 @@
{ {
"name": "luminary", "name": "luminary",
"version": "0.5.1", "version": "0.5.4",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "luminary", "name": "luminary",
"version": "0.5.1", "version": "0.5.4",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jsquash/jxl": "^1.3.0",
"exifr": "^7.1.3", "exifr": "^7.1.3",
"libraw-wasm": "^1.6.0", "libraw-wasm": "^1.6.0",
"nodemailer": "^10.6.1", "nodemailer": "^10.6.1",
"onnxruntime-node": "1.23.0",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"sharp": "^0.35.5" "sharp": "^0.35.5"
@@ -819,9 +821,6 @@
"cpu": [ "cpu": [
"arm" "arm"
], ],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -838,9 +837,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -857,9 +853,6 @@
"cpu": [ "cpu": [
"ppc64" "ppc64"
], ],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -876,9 +869,6 @@
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -895,9 +885,6 @@
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -914,9 +901,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -933,9 +917,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -952,9 +933,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -971,9 +949,6 @@
"cpu": [ "cpu": [
"arm" "arm"
], ],
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -996,9 +971,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1021,9 +993,6 @@
"cpu": [ "cpu": [
"ppc64" "ppc64"
], ],
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1046,9 +1015,6 @@
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1071,9 +1037,6 @@
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1096,9 +1059,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1121,9 +1081,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"libc": [
"musl"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1146,9 +1103,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"libc": [
"musl"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1306,6 +1260,15 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@jsquash/jxl": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@jsquash/jxl/-/jxl-1.3.0.tgz",
"integrity": "sha512-IVOPTneyOd9eBAuow+FnCYIP6wkIc7CjrCDnZGiqAPyJ63vMVxv3zoWiucGiZVh6u9vi/l40AkcS9QwkoVSAqA==",
"license": "Apache-2.0",
"dependencies": {
"wasm-feature-detect": "^1.5.1"
}
},
"node_modules/@rolldown/pluginutils": { "node_modules/@rolldown/pluginutils": {
"version": "1.0.0-beta.27", "version": "1.0.0-beta.27",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
@@ -1419,9 +1382,6 @@
"arm" "arm"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1436,9 +1396,6 @@
"arm" "arm"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1453,9 +1410,6 @@
"arm64" "arm64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1470,9 +1424,6 @@
"arm64" "arm64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1487,9 +1438,6 @@
"loong64" "loong64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1504,9 +1452,6 @@
"loong64" "loong64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1521,9 +1466,6 @@
"ppc64" "ppc64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1538,9 +1480,6 @@
"ppc64" "ppc64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1555,9 +1494,6 @@
"riscv64" "riscv64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1572,9 +1508,6 @@
"riscv64" "riscv64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1589,9 +1522,6 @@
"s390x" "s390x"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1606,9 +1536,6 @@
"x64" "x64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1623,9 +1550,6 @@
"x64" "x64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1930,6 +1854,15 @@
"url": "https://opencollective.com/vitest" "url": "https://opencollective.com/vitest"
} }
}, },
"node_modules/adm-zip": {
"version": "0.5.18",
"resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.18.tgz",
"integrity": "sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng==",
"license": "MIT",
"engines": {
"node": ">=12.0"
}
},
"node_modules/assertion-error": { "node_modules/assertion-error": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -1953,6 +1886,13 @@
"node": ">=6.0.0" "node": ">=6.0.0"
} }
}, },
"node_modules/boolean": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",
"integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",
"deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",
"license": "MIT"
},
"node_modules/browserslist": { "node_modules/browserslist": {
"version": "4.29.6", "version": "4.29.6",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz",
@@ -2087,6 +2027,40 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/define-data-property": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",
"integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",
"license": "MIT",
"dependencies": {
"es-define-property": "^1.0.0",
"es-errors": "^1.3.0",
"gopd": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/define-properties": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",
"integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",
"license": "MIT",
"dependencies": {
"define-data-property": "^1.0.1",
"has-property-descriptors": "^1.0.0",
"object-keys": "^1.1.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/detect-libc": { "node_modules/detect-libc": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -2096,6 +2070,12 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/detect-node": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",
"integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==",
"license": "MIT"
},
"node_modules/electron-to-chromium": { "node_modules/electron-to-chromium": {
"version": "1.5.492", "version": "1.5.492",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.492.tgz", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.492.tgz",
@@ -2103,6 +2083,24 @@
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-module-lexer": { "node_modules/es-module-lexer": {
"version": "1.7.0", "version": "1.7.0",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
@@ -2110,6 +2108,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/es6-error": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",
"integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==",
"license": "MIT"
},
"node_modules/esbuild": { "node_modules/esbuild": {
"version": "0.21.5", "version": "0.21.5",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
@@ -2159,6 +2163,18 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/escape-string-regexp": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
"integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/estree-walker": { "node_modules/estree-walker": {
"version": "3.0.3", "version": "3.0.3",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
@@ -2210,6 +2226,75 @@
"node": ">=6.9.0" "node": ">=6.9.0"
} }
}, },
"node_modules/global-agent": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz",
"integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==",
"license": "BSD-3-Clause",
"dependencies": {
"boolean": "^3.0.1",
"es6-error": "^4.1.1",
"matcher": "^3.0.0",
"roarr": "^2.15.3",
"semver": "^7.3.2",
"serialize-error": "^7.0.1"
},
"engines": {
"node": ">=10.0"
}
},
"node_modules/global-agent/node_modules/semver": {
"version": "7.8.6",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
"integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/globalthis": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",
"integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",
"license": "MIT",
"dependencies": {
"define-properties": "^1.2.1",
"gopd": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-property-descriptors": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",
"integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",
"license": "MIT",
"dependencies": {
"es-define-property": "^1.0.0"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/js-tokens": { "node_modules/js-tokens": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -2229,6 +2314,12 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/json-stringify-safe": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",
"integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==",
"license": "ISC"
},
"node_modules/json5": { "node_modules/json5": {
"version": "2.2.3", "version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
@@ -2287,6 +2378,18 @@
"@jridgewell/sourcemap-codec": "^1.5.5" "@jridgewell/sourcemap-codec": "^1.5.5"
} }
}, },
"node_modules/matcher": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",
"integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==",
"license": "MIT",
"dependencies": {
"escape-string-regexp": "^4.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.1.3", "version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -2332,6 +2435,38 @@
"node": ">=20.0.0" "node": ">=20.0.0"
} }
}, },
"node_modules/object-keys": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
"integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/onnxruntime-common": {
"version": "1.23.0",
"resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.23.0.tgz",
"integrity": "sha512-Auz8S9D7vpF8ok7fzTobvD1XdQDftRf/S7pHmjeCr3Xdymi4z1C7zx4vnT6nnUjbpelZdGwda0BmWHCCTMKUTg==",
"license": "MIT"
},
"node_modules/onnxruntime-node": {
"version": "1.23.0",
"resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.23.0.tgz",
"integrity": "sha512-j7QVuR4ouektZjOopKtXcIGsB3C6R9kVbgS10lc2e5SxoWMUhmCwxNl4qBslpWJaPrFxvrQrQaQLQdqku8V19w==",
"hasInstallScript": true,
"license": "MIT",
"os": [
"win32",
"darwin",
"linux"
],
"dependencies": {
"adm-zip": "^0.5.16",
"global-agent": "^3.0.0",
"onnxruntime-common": "1.23.0"
}
},
"node_modules/pathe": { "node_modules/pathe": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz", "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
@@ -2420,6 +2555,23 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/roarr": {
"version": "2.15.4",
"resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",
"integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==",
"license": "BSD-3-Clause",
"dependencies": {
"boolean": "^3.0.1",
"detect-node": "^2.0.4",
"globalthis": "^1.0.1",
"json-stringify-safe": "^5.0.1",
"semver-compare": "^1.0.0",
"sprintf-js": "^1.1.2"
},
"engines": {
"node": ">=8.0"
}
},
"node_modules/rollup": { "node_modules/rollup": {
"version": "4.68.7", "version": "4.68.7",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.7.tgz", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.7.tgz",
@@ -2485,6 +2637,27 @@
"semver": "bin/semver.js" "semver": "bin/semver.js"
} }
}, },
"node_modules/semver-compare": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",
"integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==",
"license": "MIT"
},
"node_modules/serialize-error": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz",
"integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==",
"license": "MIT",
"dependencies": {
"type-fest": "^0.13.1"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/sharp": { "node_modules/sharp": {
"version": "0.35.5", "version": "0.35.5",
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
@@ -2563,6 +2736,12 @@
"node": ">=6.0.0" "node": ">=6.0.0"
} }
}, },
"node_modules/sprintf-js": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
"integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",
"license": "BSD-3-Clause"
},
"node_modules/stackback": { "node_modules/stackback": {
"version": "0.0.2", "version": "0.0.2",
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
@@ -2628,6 +2807,18 @@
"license": "0BSD", "license": "0BSD",
"optional": true "optional": true
}, },
"node_modules/type-fest": {
"version": "0.13.1",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",
"integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==",
"license": "(MIT OR CC0-1.0)",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/typescript": { "node_modules/typescript": {
"version": "5.9.3", "version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
@@ -2822,6 +3013,12 @@
} }
} }
}, },
"node_modules/wasm-feature-detect": {
"version": "1.10.1",
"resolved": "https://registry.npmjs.org/wasm-feature-detect/-/wasm-feature-detect-1.10.1.tgz",
"integrity": "sha512-+wz9+WpMKgQ7H1tm41nJbFwAvwX4DqY0jNY8Blw5Qe6hHg1yhCJ+AqU0R4lgX7p3pyo8irYIl1+mMNoBwSj2Zg==",
"license": "Apache-2.0"
},
"node_modules/why-is-node-running": { "node_modules/why-is-node-running": {
"version": "2.3.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+6 -2
View File
@@ -2,13 +2,15 @@
"name": "luminary", "name": "luminary",
"private": true, "private": true,
"license": "MIT", "license": "MIT",
"version": "0.5.1", "version": "0.5.4",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"server": "node server/index.mjs", "server": "node server/index.mjs",
"server:dev": "node --watch server/index.mjs", "server:dev": "node --watch server/index.mjs",
"build": "tsc --noEmit && vite build", "build": "tsc --noEmit && vite build && node scripts/precompress.mjs",
"precompress": "node scripts/precompress.mjs",
"backup": "node scripts/backup.mjs",
"start": "node server/index.mjs", "start": "node server/index.mjs",
"preview": "vite preview", "preview": "vite preview",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
@@ -19,9 +21,11 @@
"build:lens-db": "node scripts/build-lens-db.mjs" "build:lens-db": "node scripts/build-lens-db.mjs"
}, },
"dependencies": { "dependencies": {
"@jsquash/jxl": "^1.3.0",
"exifr": "^7.1.3", "exifr": "^7.1.3",
"libraw-wasm": "^1.6.0", "libraw-wasm": "^1.6.0",
"nodemailer": "^10.6.1", "nodemailer": "^10.6.1",
"onnxruntime-node": "1.23.0",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"sharp": "^0.35.5" "sharp": "^0.35.5"
Binary file not shown.
+185
View File
@@ -0,0 +1,185 @@
/**
* Catalog backups without stopping the server.
*
* `VACUUM INTO` writes a consistent copy of the live SQLite database (including
* everything still in the WAL), so a backup is safe while people are editing.
* Originals are large, so copying them is opt-in: previews, thumbnails and
* denoise renders are all regenerable, originals are not.
*
* npm run backup # database only, keep 14
* npm run backup -- --with-originals # also copy originals/ (can be huge)
* npm run backup -- --keep 30 --dir /mnt/backups
*
* Restore: stop the server, put the `catalog-*.db` snapshot back as lumenroom.db
* (delete the old -wal/-shm files) and copy the originals snapshot back into the
* storage root.
*/
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
function argValue(name, fallback) {
const index = process.argv.indexOf(`--${name}`);
if (index < 0) return fallback;
const value = process.argv[index + 1];
return value && !value.startsWith('--') ? value : fallback;
}
const DATA_DIR = path.resolve(
process.env.LUMINARY_DATA || process.env.LUMENROOM_DATA || path.join(ROOT, 'server', 'data'),
);
const DB_PATH = path.join(DATA_DIR, 'lumenroom.db');
const BACKUP_DIR = path.resolve(
argValue('dir', process.env.LUMINARY_BACKUP_DIR || path.join(DATA_DIR, 'backups')),
);
const KEEP = Math.max(1, Number(argValue('keep', process.env.LUMINARY_BACKUP_KEEP || '14')) || 14);
const WITH_ORIGINALS = process.argv.includes('--with-originals');
const pad = (value) => String(value).padStart(2, '0');
const now = new Date();
const stamp = [
now.getFullYear(),
pad(now.getMonth() + 1),
pad(now.getDate()),
'-',
pad(now.getHours()),
pad(now.getMinutes()),
pad(now.getSeconds()),
].join('');
const fmt = (bytes) => {
if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(2)} GB`;
if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
return `${bytes} B`;
};
/** The admin may have moved image files out of DATA_DIR; the catalog knows. */
function storageRoot() {
const db = new DatabaseSync(DB_PATH, { readOnly: true });
try {
const row = db.prepare("SELECT value FROM kv WHERE key = 'storageRoot'").get();
if (!row?.value) return DATA_DIR;
const parsed = JSON.parse(row.value);
return typeof parsed === 'string' && parsed.trim() ? path.resolve(parsed) : DATA_DIR;
} catch {
return DATA_DIR;
} finally {
db.close();
}
}
async function prune(prefix, keep) {
let names = [];
try {
names = (await fsp.readdir(BACKUP_DIR)).filter((name) => name.startsWith(prefix));
} catch {
return 0;
}
names.sort();
const stale = names.slice(0, Math.max(0, names.length - keep));
for (const name of stale) {
await fsp.rm(path.join(BACKUP_DIR, name), { recursive: true, force: true });
}
return stale.length;
}
if (!fs.existsSync(DB_PATH)) {
console.error(`backup: no catalog at ${DB_PATH}`);
process.exit(1);
}
await fsp.mkdir(BACKUP_DIR, { recursive: true });
/* --------------------------------------------------------- database snapshot */
const snapshot = path.join(BACKUP_DIR, `catalog-${stamp}.db`);
const db = new DatabaseSync(DB_PATH);
let counts;
try {
// VACUUM INTO is a consistent point-in-time copy and also compacts it.
db.exec(`VACUUM INTO '${snapshot.replaceAll("'", "''")}'`);
counts = {
users: Number(db.prepare('SELECT COUNT(*) AS n FROM users').get()?.n ?? 0),
events: Number(db.prepare('SELECT COUNT(*) AS n FROM events').get()?.n ?? 0),
photos: Number(db.prepare('SELECT COUNT(*) AS n FROM photos').get()?.n ?? 0),
};
} catch (err) {
console.error(`backup: could not snapshot the catalog: ${err.message}`);
process.exit(1);
} finally {
db.close();
}
/* Verify the copy opens and is internally consistent before trusting it. */
const check = new DatabaseSync(snapshot, { readOnly: true });
let integrity = 'unknown';
try {
integrity = String(check.prepare('PRAGMA integrity_check').get()?.integrity_check ?? 'unknown');
} finally {
check.close();
}
if (integrity !== 'ok') {
console.error(`backup: snapshot failed its integrity check (${integrity})`);
process.exit(1);
}
const dbBytes = (await fsp.stat(snapshot)).size;
let copiedOriginals = null;
let originalsBytes = 0;
/* ---------------------------------------------------------------- originals */
if (WITH_ORIGINALS) {
const source = path.join(storageRoot(), 'originals');
const target = path.join(BACKUP_DIR, `originals-${stamp}`);
try {
await fsp.cp(source, target, { recursive: true, force: true });
for (const name of await fsp.readdir(target)) {
const stat = await fsp.stat(path.join(target, name)).catch(() => null);
if (stat?.isFile()) originalsBytes += stat.size;
}
copiedOriginals = target;
} catch (err) {
console.error(`backup: catalog saved, but copying originals failed: ${err.message}`);
process.exitCode = 1;
}
}
await fsp.writeFile(
path.join(BACKUP_DIR, `manifest-${stamp}.json`),
`${JSON.stringify(
{
kind: 'luminary-backup',
version: 1,
createdAt: now.toISOString(),
catalog: path.basename(snapshot),
counts,
bytes: dbBytes,
originals: copiedOriginals ? { path: path.basename(copiedOriginals), bytes: originalsBytes } : null,
storageRoot: storageRoot(),
},
null,
2,
)}\n`,
);
const prunedDb = await prune('catalog-', KEEP);
const prunedOriginals = WITH_ORIGINALS ? await prune('originals-', KEEP) : 0;
const prunedManifests = await prune('manifest-', KEEP);
console.log(`backup: ${snapshot}`);
console.log(
` ${fmt(dbBytes)} · ${counts.users} user(s), ${counts.events} event(s), ${counts.photos} photo record(s)`,
);
if (copiedOriginals) console.log(` originals: ${copiedOriginals} (${fmt(originalsBytes)})`);
const pruned = prunedDb + prunedOriginals + prunedManifests;
if (pruned) console.log(` pruned ${pruned} old file(s), keeping ${KEEP}`);
if (!WITH_ORIGINALS) {
console.log(
` note: original files were not copied; run with --with-originals or rsync ${path.join(storageRoot(), 'originals')}`,
);
}
+6
View File
@@ -122,6 +122,12 @@ function main() {
const sudoLines = SUDO_PASS ? `${SUDO_PASS}\n${SUDO_PASS}\n` : undefined; const sudoLines = SUDO_PASS ? `${SUDO_PASS}\n${SUDO_PASS}\n` : undefined;
const script = [ const script = [
`cd ${REMOTE_PATH} || exit 3`, `cd ${REMOTE_PATH} || exit 3`,
// node_modules is excluded from the rsync, so a new dependency in the
// lockfile would otherwise fail the build on a server that has never
// installed it. Installed as the login user: the checkout belongs to them.
'npm ci --no-audit --no-fund',
'deps=$?',
'[ "$deps" -eq 0 ] || { echo "deploy: remote npm ci failed ($deps)"; exit "$deps"; }',
`${sudo}npm run build`, `${sudo}npm run build`,
'build=$?', 'build=$?',
'[ "$build" -eq 0 ] || { echo "deploy: remote build failed ($build)"; exit "$build"; }', '[ "$build" -eq 0 ] || { echo "deploy: remote build failed ($build)"; exit "$build"; }',
+93
View File
@@ -0,0 +1,93 @@
/**
* Writes `.br` and `.gz` copies of the text assets next to the built files.
*
* The server serves those directly when a browser offers an encoding, so no
* request ever pays for compression: `index-*.js` is ~780 kB raw and ~240 kB
* gzipped, which is the difference between a slow and a normal first load.
* Images and fonts are already compressed and are left alone.
*/
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import zlib from 'node:zlib';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const DIST = path.join(ROOT, 'dist');
const MIN_BYTES = 1024;
const COMPRESSIBLE = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.json', '.map', '.txt', '.xml', '.webmanifest']);
const brotliOptions = {
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]: 11,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: 0,
},
};
async function* walk(dir) {
for (const entry of await fsp.readdir(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) yield* walk(full);
else if (entry.isFile()) yield full;
}
}
function isStale(source, target) {
try {
const out = fs.statSync(target);
return out.mtimeMs < fs.statSync(source).mtimeMs;
} catch {
return true;
}
}
async function compressFile(file, totals) {
const ext = path.extname(file).toLowerCase();
if (!COMPRESSIBLE.has(ext)) return 0;
const stat = await fsp.stat(file);
if (stat.size < MIN_BYTES) return 0;
const raw = await fsp.readFile(file);
let files = 0;
for (const variant of ['gz', 'br']) {
const target = `${file}.${variant}`;
if (!isStale(file, target)) continue;
const body =
variant === 'gz'
? zlib.gzipSync(raw, { level: 9 })
: zlib.brotliCompressSync(raw, {
...brotliOptions,
params: {
...brotliOptions.params,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: raw.length,
},
});
// A "compressed" file that is larger than the original is never served.
if (body.length >= raw.length) {
await fsp.rm(target, { force: true });
continue;
}
await fsp.writeFile(target, body);
files += 1;
totals[variant] += raw.length - body.length;
}
return files;
}
if (!fs.existsSync(DIST)) {
console.error('precompress: dist/ is missing — run "vite build" first');
process.exit(1);
}
const totals = { gz: 0, br: 0 };
let files = 0;
for await (const file of walk(DIST)) {
files += await compressFile(file, totals);
}
const kb = (bytes) => `${Math.round(bytes / 1024)} kB`;
console.log(
`precompress: wrote ${files} variant(s); a full load saves ${kb(totals.gz)} with gzip or ${kb(totals.br)} with brotli`,
);
+41 -1
View File
@@ -379,6 +379,26 @@ try {
const lensTintOn = pixelAt(0.625, 0.469); const lensTintOn = pixelAt(0.625, 0.469);
const lensTintOff = pixelAt(0.7, 0.469); const lensTintOff = pixelAt(0.7, 0.469);
// Before / after split: the edit is drawn full-frame, then the untouched
// source is painted over the left slice. Reading the same band either side of
// the line must give the moved slider on the right and the default on the
// left, which is what proves the scissor lands where the drag line sits.
const splitAfter = defaultEdits();
splitAfter.exposure = 2;
renderer.render(splitAfter, { width: w, height: h });
const splitAfterFull = pixelAt(0.75, 0.5);
renderer.render(defaultEdits(), { width: w, height: h });
const splitBeforeFull = pixelAt(0.75, 0.5);
renderer.render(splitAfter, { width: w, height: h });
renderer.render(defaultEdits(), {
width: w,
height: h,
scissor: { x: 0, w: Math.round(w / 2) },
});
const splitLeft = pixelAt(0.25, 0.5);
const splitRight = pixelAt(0.75, 0.5);
const sameRgb = (a, b) => a.every((v, i) => Math.abs(v - b[i]) <= 1);
pre.textContent = 'RESULT ' + JSON.stringify({ pre.textContent = 'RESULT ' + JSON.stringify({
clipPixels, clipPixels,
clipRed: near(clipPixels[0], RED_MARK), clipRed: near(clipPixels[0], RED_MARK),
@@ -437,6 +457,14 @@ try {
cropDetailBounded: Math.abs(cropDetailOff[2] - cropRefOff[2]) <= 3, cropDetailBounded: Math.abs(cropDetailOff[2] - cropRefOff[2]) <= 3,
lensTintAligned: lensTintOn[0] > lensRef[0] + 40, lensTintAligned: lensTintOn[0] > lensRef[0] + 40,
lensTintBounded: Math.abs(lensTintOff[0] - lensRefOff[0]) <= 2, lensTintBounded: Math.abs(lensTintOff[0] - lensRefOff[0]) <= 2,
splitLeft,
splitRight,
splitBeforeFull,
splitAfterFull,
splitShowsBoth:
sameRgb(splitLeft, splitBeforeFull) &&
sameRgb(splitRight, splitAfterFull) &&
!sameRgb(splitAfterFull, splitBeforeFull),
tintStrengthWorks: tintFull[2] > tintCore[2] + 8, tintStrengthWorks: tintFull[2] > tintCore[2] + 8,
tintOffMatches: Math.abs(tintOffPixel[2] - dabSoft[2]) <= 1, tintOffMatches: Math.abs(tintOffPixel[2] - dabSoft[2]) <= 1,
// A hard dab covers the core, and even an 80 % feather stops at the rim. // A hard dab covers the core, and even an 80 % feather stops at the rim.
@@ -702,6 +730,14 @@ async function main() {
); );
return 1; return 1;
} }
if (!result.splitShowsBoth) {
console.error(
'render check FAILED: the before / after split does not follow its drag line ' +
`(left=${JSON.stringify(result.splitLeft)} vs ${JSON.stringify(result.splitBeforeFull)}, ` +
`right=${JSON.stringify(result.splitRight)} vs ${JSON.stringify(result.splitAfterFull)}).`,
);
return 1;
}
if ( if (
!result.dabCoreDarkened || !result.dabCoreDarkened ||
!result.dabSoftCoreDarkened || !result.dabSoftCoreDarkened ||
@@ -722,7 +758,11 @@ async function main() {
return 1; return 1;
} }
console.log( console.log(
'render check PASSED: proxy and sidecar share a row order and the clipping overlay names the channels.', `render check: before / after split left=${JSON.stringify(result.splitLeft)}` +
` right=${JSON.stringify(result.splitRight)}`,
);
console.log(
'render check PASSED: proxy and sidecar share a row order, the clipping overlay names the channels, and the split keeps each side to its own edit.',
); );
return 0; return 0;
} }
+54
View File
@@ -0,0 +1,54 @@
/**
* Runs the camera-to-sRGB conversion off the main thread when it can.
*
* The conversion is CPU-bound and synchronous, so at four parallel imports it
* was the widest serial section left in the pipeline: four 24 MP frames cost
* ~10 s of event-loop time on top of the demosaic. A worker takes that loop off
* the main thread while the decoder pool and zlib keep their own threads.
*
* The frame is shared rather than transferred: `toRgb` allocates both buffers
* on SharedArrayBuffer, so `postMessage` hands over views and the worker writes
* the same memory the encoder will read. A frame that is not shared (a caller
* outside the raw pipeline) stays on this thread instead of being copied.
*/
import { Worker } from 'node:worker_threads';
import { cameraToProxy } from './color.mjs';
function isShared(view) {
return view?.buffer instanceof SharedArrayBuffer;
}
function runInWorker(rgb16, rgb8, matrix) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./color-worker.mjs', import.meta.url), {
workerData: { rgb16, rgb8, matrix },
});
let settled = false;
const finish = (fn, value) => {
if (settled) return;
settled = true;
worker.terminate().catch(() => {});
fn(value);
};
worker.once('message', (message) => {
if (message?.error) finish(reject, new Error(message.error));
else finish(resolve, message?.gain);
});
worker.once('error', (error) => finish(reject, error));
worker.once('exit', (code) => {
// A clean exit arrives after the message; only a crash before it is an error.
if (code !== 0) finish(reject, new Error(`colour worker exited with code ${code}`));
});
});
}
/**
* Applies the camera matrix to the frame in place and resolves with the white
* point gain, exactly like `cameraToProxy`. A worker failure rejects rather
* than re-running the conversion here: the worker may have written part of the
* frame, and applying it again would double the white point.
*/
export async function cameraToProxyAsync(rgb16, rgb8, matrix) {
if (!isShared(rgb16) || !isShared(rgb8)) return cameraToProxy(rgb16, rgb8, matrix);
return runInWorker(rgb16, rgb8, matrix);
}
+17
View File
@@ -0,0 +1,17 @@
/**
* Off-main-thread camera-to-proxy conversion.
*
* `cameraToProxy` is a pixel loop over the whole frame: 2.4 s on a 24 MP decode
* here, and four parallel imports serialised on it. The buffers arrive as
* SharedArrayBuffer views, so the worker mutates the frame in place and nothing
* is copied across the thread boundary.
*/
import { parentPort, workerData } from 'node:worker_threads';
import { cameraToProxy } from './color.mjs';
try {
const gain = cameraToProxy(workerData.rgb16, workerData.rgb8, workerData.matrix);
parentPort.postMessage({ gain });
} catch (error) {
parentPort.postMessage({ error: error instanceof Error ? error.message : String(error) });
}
+14
View File
@@ -107,3 +107,17 @@ export const RAW_WORKERS = Math.max(
/** Idle decoder workers are disposed after this long to release memory. */ /** Idle decoder workers are disposed after this long to release memory. */
export const RAW_IDLE_MS = Number(setting('RAW_IDLE_MS', '90000')); export const RAW_IDLE_MS = Number(setting('RAW_IDLE_MS', '90000'));
/**
* Demosaic setting for Fujifilm X-Trans sensors. LibRaw reads `userQual` as
* Markesteijn passes for X-Trans, and the 3-pass default costs about 50 s on a
* 40 MP frame while 1-pass costs about 9 s. The proxy is downsampled to
* RAW_PREVIEW_EDGE, so the difference does not survive to the editor.
*/
export const RAW_XTRANS_QUALITY = Math.min(
3,
Math.max(1, Number(setting('RAW_XTRANS_QUALITY', '1')) || 1),
);
/** Ceiling on one demosaic, measured from when a worker picks the job up. */
export const RAW_TIMEOUT_MS = Number(setting('RAW_TIMEOUT_MS', '120000'));
+17 -4
View File
@@ -10,10 +10,10 @@ import { parentPort, workerData } from 'node:worker_threads';
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import sharp from 'sharp'; import sharp from 'sharp';
import { denoiseRgb } from './denoise/rgbPipeline.ts'; import { denoiseRgb } from './denoise/rgbPipeline.ts';
import { guidedDenoiser } from './denoise/standin.ts'; import { createBaseDenoiser } from './denoise/baseDenoiser.ts';
try { try {
const { sourcePath, outPath } = workerData; const { sourcePath, outPath, base = 'guided' } = workerData;
const buffer = await fs.readFile(sourcePath); const buffer = await fs.readFile(sourcePath);
const { data, info } = await sharp(buffer) const { data, info } = await sharp(buffer)
.rotate() .rotate()
@@ -37,8 +37,21 @@ try {
const started = performance.now(); const started = performance.now();
// Always full strength: the Amount slider blends on the client, so one render // Always full strength: the Amount slider blends on the client, so one render
// serves every setting and the cache key does not move with the slider. // serves every setting and the cache key does not move with the slider. The
const out = await denoiseRgb({ rgb, width, height }, { amount: 1 }, guidedDenoiser()); // base denoiser (guided / nlm / scunet) is chosen by the request; the cache
// key already folds it in, so a different model is a different render.
//
// Progress is the only window the panel has into a 95 s SCUNet run, so both
// the stage boundaries and the tile counter are forwarded to the job.
const report = (progress) => parentPort?.postMessage({ type: 'progress', progress });
const out = await denoiseRgb(
{ rgb, width, height },
{ amount: 1 },
createBaseDenoiser(base, (tiles) =>
report({ stage: 'base', done: tiles.done, total: tiles.total }),
),
(stage) => report({ stage }),
);
// 4:4:4 so the chroma work is not immediately thrown away by the encoder. // 4:4:4 so the chroma work is not immediately thrown away by the encoder.
const jpeg = await sharp(Buffer.from(out.rgb), { raw: { width, height, channels: 3 } }) const jpeg = await sharp(Buffer.from(out.rgb), { raw: { width, height, channels: 3 } })
.jpeg({ quality: 95, chromaSubsampling: '4:4:4' }) .jpeg({ quality: 95, chromaSubsampling: '4:4:4' })
+28 -16
View File
@@ -1,11 +1,13 @@
/** /**
* Job runner for the detail-preserving denoise. * Job runner for the detail-preserving denoise.
* *
* `server/denoise/` is a verbatim copy of the dependency-free pipeline from the * `server/denoise/` starts from the dependency-free pipeline of the raw-noise
* raw-noise package. It reconstructs from a per-pixel crossfade between the * package, which supplies the Guided and NLM bases; SCUNet runs the same stages
* source and a denoised base, so the result is bounded by the original pixels and * around an ONNX model. Every base is reconstructed from a per-pixel crossfade
* cannot ring or overshoot; flat noise is replaced, structure is given back * between the source and the denoised base, so the result is bounded by the
* verbatim. The GPU's own `noise` sliders are a separate, much simpler path. * original pixels and cannot ring or overshoot; flat noise is replaced, structure
* is given back verbatim. The GPU's own `noise` sliders are a separate, much
* simpler path.
* *
* Three things here are deliberate: * Three things here are deliberate:
* *
@@ -33,6 +35,9 @@ export function clearDenoised(photoId) {
return removeDenoised(photoId); return removeDenoised(photoId);
} }
/** Every base the picker offers; the cache keeps one render for each of them. */
export const DENOISE_BASES = ['guided', 'scunet', 'nlm'];
/** /**
* Bump whenever the copied modules under `server/denoise/` change output. The key * Bump whenever the copied modules under `server/denoise/` change output. The key
* is the only thing between a fixed pipeline and a stale cached file. * is the only thing between a fixed pipeline and a stale cached file.
@@ -59,23 +64,23 @@ export function getDenoiseJob(id) {
return jobs.get(id) ?? null; return jobs.get(id) ?? null;
} }
/** Stable for a photo and a pipeline version -- Amount is the client's business. */ /** Stable for a photo, a pipeline version and a base denoiser -- Amount is the client's business. */
export function denoiseKey(photoId) { export function denoiseKey(photoId, base = 'guided') {
return crypto return crypto
.createHash('sha1') .createHash('sha1')
.update(`${photoId}|${PIPELINE_VERSION}`) .update(`${photoId}|${PIPELINE_VERSION}|${base}`)
.digest('hex') .digest('hex')
.slice(0, 12); .slice(0, 12);
} }
export function startDenoise({ photoId, sourcePath }) { export function startDenoise({ photoId, sourcePath, base = 'guided' }) {
const key = denoiseKey(photoId); const key = denoiseKey(photoId, base);
const joined = byKey.get(key); const joined = byKey.get(key);
if (joined) return joined; if (joined) return joined;
const url = `/api/photos/${encodeURIComponent(photoId)}/denoised?v=${key}`; const url = `/api/photos/${encodeURIComponent(photoId)}/denoised?v=${key}`;
const job = { id: crypto.randomUUID(), photoId, key, state: 'running', startedAt: Date.now() }; const job = { id: crypto.randomUUID(), photoId, key, base, state: 'running', startedAt: Date.now() };
// Re-running after the edit was cleared, or a second browser, should not pay // Re-running after the edit was cleared, or a second browser, should not pay
// for the CPU again. The file is the cache; the job just reports it. // for the CPU again. The file is the cache; the job just reports it.
@@ -108,19 +113,26 @@ function run(job) {
active += 1; active += 1;
const outPath = denoisedPath(job.photoId, job.key); const outPath = denoisedPath(job.photoId, job.key);
const worker = new Worker(new URL('./denoise-worker.mjs', import.meta.url), { const worker = new Worker(new URL('./denoise-worker.mjs', import.meta.url), {
workerData: { sourcePath: job.sourcePath, outPath }, workerData: { sourcePath: job.sourcePath, outPath, base: job.base },
}); });
worker.on('message', (message) => { worker.on('message', (message) => {
if (message?.type === 'done') { if (message?.type === 'progress') {
job.progress = message.progress;
} else if (message?.type === 'done') {
job.state = 'done'; job.state = 'done';
job.progress = null;
job.ms = message.ms; job.ms = message.ms;
job.bytes = message.bytes; job.bytes = message.bytes;
job.stats = message.stats; job.stats = message.stats;
// A version bump (or an older build) leaves its render behind; keep the // A version bump (or an older build) leaves its render behind. Keep the
// current one and drop the rest so the folder cannot grow without bound. // current key of every base and drop only the older ones, so switching
// models reuses its cached render instead of paying for the CPU again.
try { try {
removeDenoised(job.photoId, job.key); removeDenoised(
job.photoId,
DENOISE_BASES.map((base) => denoiseKey(job.photoId, base)),
);
} catch { } catch {
/* cleanup is best effort -- never fail a finished job over it */ /* cleanup is best effort -- never fail a finished job over it */
} }
+38
View File
@@ -0,0 +1,38 @@
/**
* Resolve a base denoiser by name -- the slot the pipeline calls as `runBase`.
*
* Three choices, all occupying the same interface from `standin.ts`:
*
* - `guided` (default): the classical guided filter. Fast, edge-preserving,
* the current shipping path.
* - `nlm`: non-local means. Slower, the quality reference the model must beat.
* - `scunet`: the learned SCUNet model, run tiled with overlap-add.
*
* Constructing is free: the ONNX session is created lazily on first use, so the
* model selector can show all three even before a run ever picks SCUNet. A
* missing model surfaces as a clear error at run time, not at import time.
*/
import { fileURLToPath } from 'node:url';
import { guidedDenoiser, nlmDenoiser, type BaseDenoiser } from './standin.ts';
import { createOnnxBaseDenoiser, type TileProgress } from './onnx.ts';
export type BaseDenoiserName = 'guided' | 'nlm' | 'scunet';
/** The SCUNet weights shipped with the server, next to this file. */
const SCUNET_MODEL = fileURLToPath(new URL('./scunet_color_25.onnx', import.meta.url));
export function createBaseDenoiser(
base: BaseDenoiserName,
onProgress?: (progress: TileProgress) => void,
): BaseDenoiser {
switch (base) {
case 'nlm':
return nlmDenoiser();
case 'scunet':
return createOnnxBaseDenoiser({ modelPath: SCUNET_MODEL, tile: 256, overlap: 32, onProgress });
case 'guided':
default:
return guidedDenoiser();
}
}
+205
View File
@@ -0,0 +1,205 @@
/**
* Tiled ONNX inference for the base plane -- the SCUNet path.
*
* This is the only file that may import `onnxruntime-node`, and it imports it
* lazily: nothing here requires a model to exist until a denoiser is actually
* asked to run. The classical stand-ins (`guided`, `nlm`) occupy the same slot
* and need no model at all, so the model selector is safe to show even before a
* run ever selects SCUNet.
*
* The model contract is fixed and small:
*
* input 1 x 3 x TILE x TILE float32, RGB in 0..1
* output 1 x 3 x TILE x TILE float32, same
*
* `runTiled` is separated from the session so the tiling, padding, feathering
* and normalisation can be reasoned about independently of ORT.
*/
import type { BaseDenoiser, BaseImage } from './standin.ts';
/** Runs one `tile x tile`, 3-channel tile. Input and output are interleaved RGB. */
export type RgbTileRunner = (input: Float32Array, tile: number) => Promise<Float32Array>;
export interface TileProgress {
done: number;
total: number;
}
export interface OnnxBaseOptions {
modelPath: string;
/** Fixed square size the graph was exported at. Must match the graph. */
tile?: number;
/** Overlap in pixels between neighbouring tiles. */
overlap?: number;
/** Defaults to physical cores. Keep it below the host's raw decode pool. */
intraOpThreads?: number;
/** Called after each tile lands, so a long run can report where it is. */
onProgress?: (progress: TileProgress) => void;
}
/**
* Raised-cosine feather along one axis, floored so no pixel is weighted zero.
*
* The floor matters: at the image border a tile is the only contributor, and a
* zero weight there would divide 0 by 0.
*/
export function featherWeights(tile: number, overlap: number): Float32Array {
const weights = new Float32Array(tile).fill(1);
const edge = Math.min(Math.max(0, overlap), Math.floor(tile / 2));
for (let i = 0; i < edge; i++) {
const t = (i + 0.5) / edge;
weights[i] = Math.max(0.5 - 0.5 * Math.cos(Math.PI * t), 1e-3);
weights[tile - 1 - i] = weights[i];
}
return weights;
}
/** Tiled inference with overlap-add and feathering. */
export async function runTiled(
runTile: RgbTileRunner,
image: BaseImage,
tile: number,
overlap: number,
onProgress?: (progress: TileProgress) => void,
): Promise<BaseImage> {
const { width, height } = image;
if (!Number.isInteger(tile) || tile < 8) throw new Error(`tile must be an integer >= 8, got ${tile}`);
if (overlap < 0 || overlap >= tile) throw new Error(`overlap must be in [0, tile), got ${overlap}`);
const expected = 3 * tile * tile;
const step = tile - overlap;
const weights = featherWeights(tile, overlap);
const acc = new Float32Array(3 * width * height);
const weight = new Float32Array(width * height);
const patch = new Float32Array(expected);
// Tiles start every `step` pixels, so the last one may hang off the edge.
const total = Math.ceil(width / step) * Math.ceil(height / step);
let done = 0;
for (let ty = 0; ty < height; ty += step) {
for (let tx = 0; tx < width; tx += step) {
// Gather with clamp-to-edge padding; the convolution needs a full tile
// even when the tile hangs off the right or bottom edge.
for (let y = 0; y < tile; y++) {
const sy = ty + y;
const cy = sy < 0 ? 0 : sy >= height ? height - 1 : sy;
for (let x = 0; x < tile; x++) {
const sx = tx + x;
const cx = sx < 0 ? 0 : sx >= width ? width - 1 : sx;
const src = (cy * width + cx) * 3;
const dst = (y * tile + x) * 3;
patch[dst] = image.rgb[src];
patch[dst + 1] = image.rgb[src + 1];
patch[dst + 2] = image.rgb[src + 2];
}
}
const out = await runTile(patch, tile);
if (out.length !== expected) {
throw new Error(`tile runner returned ${out.length} values, expected ${expected}`);
}
for (let y = 0; y < tile; y++) {
const sy = ty + y;
if (sy < 0 || sy >= height) continue;
for (let x = 0; x < tile; x++) {
const sx = tx + x;
if (sx < 0 || sx >= width) continue;
const w = weights[y] * weights[x];
const dst = (sy * width + sx) * 3;
const src = (y * tile + x) * 3;
acc[dst] += out[src] * w;
acc[dst + 1] += out[src + 1] * w;
acc[dst + 2] += out[src + 2] * w;
weight[sy * width + sx] += w;
}
}
done += 1;
onProgress?.({ done, total });
}
}
const rgb = new Float32Array(3 * width * height);
for (let i = 0, p = 0; i < width * height; i++, p += 3) {
const w = weight[i] || 1;
for (let k = 0; k < 3; k++) {
const v = acc[p + k] / w;
rgb[p + k] = v < 0 ? 0 : v > 255 ? 255 : v;
}
}
return { rgb, width, height };
}
interface Session {
run(feeds: Record<string, unknown>): Promise<Record<string, { data: Float32Array }>>;
inputNames: readonly string[];
outputNames: readonly string[];
}
/**
* Build a `BaseDenoiser` backed by an ONNX model.
*
* The session is created on first use and memoised, so constructing this is
* free and a missing model surfaces as a clear error at run time rather than at
* import time.
*/
export function createOnnxBaseDenoiser(options: OnnxBaseOptions): BaseDenoiser {
const tile = options.tile ?? 256;
const overlap = options.overlap ?? 32;
let sessionPromise: Promise<Session> | null = null;
const session = (): Promise<Session> => {
if (!sessionPromise) {
sessionPromise = (async () => {
const ort = await import('onnxruntime-node');
const created = await ort.InferenceSession.create(options.modelPath, {
executionProviders: ['cpu'],
graphOptimizationLevel: 'all',
intraOpNumThreads: options.intraOpThreads ?? 0,
});
return created as unknown as Session;
})();
}
return sessionPromise;
};
return async (image: BaseImage): Promise<BaseImage> => {
const active = await session();
const ort = await import('onnxruntime-node');
const inputName = active.inputNames[0];
const outputName = active.outputNames[0];
if (!inputName || !outputName) throw new Error('model has no input/output');
// The model expects 0..1; everything above works in 0..255.
//
// But the two sides disagree about layout: `runTiled` is interleaved (HWC),
// while every published denoiser is NCHW (`1x3xTILExTILE`). Handing HWC bytes
// to a `[1,3,T,T]` tensor does not throw -- it silently feeds a scrambled
// image, so channel 0 holds a third of every row rather than red. The output
// needs the mirror transpose for the same reason.
const plane = tile * tile;
const runTile: RgbTileRunner = async (input, size) => {
const normalised = new Float32Array(3 * plane);
for (let p = 0, i = 0; p < plane; p++, i += 3) {
normalised[p] = input[i] / 255;
normalised[plane + p] = input[i + 1] / 255;
normalised[2 * plane + p] = input[i + 2] / 255;
}
const tensor = new ort.Tensor('float32', normalised, [1, 3, size, size]);
const result = await active.run({ [inputName]: tensor });
const output = result[outputName]?.data;
if (!output) throw new Error(`model produced no output named ${outputName}`);
const scaled = new Float32Array(output.length);
for (let p = 0, i = 0; p < plane; p++, i += 3) {
scaled[i] = output[p] * 255;
scaled[i + 1] = output[plane + p] * 255;
scaled[i + 2] = output[2 * plane + p] * 255;
}
return scaled;
};
return runTiled(runTile, image, tile, overlap, options.onProgress);
};
}
+12
View File
@@ -105,6 +105,13 @@ export interface DenoiseStats {
timings: StageTimings; timings: StageTimings;
} }
/**
* Where a run currently is. The base stage is the expensive one (SCUNet runs it
* tile by tile); the rest are seconds at most, but naming them beats a dead
* spinner while the base is between tiles.
*/
export type DenoiseStage = 'analyse' | 'base' | 'gate' | 'render';
export interface DenoiseOutput { export interface DenoiseOutput {
rgb: Uint8Array; rgb: Uint8Array;
/** Luma of the denoised base, before detail re-injection, for inspection. */ /** Luma of the denoised base, before detail re-injection, for inspection. */
@@ -184,6 +191,7 @@ export async function denoiseRgb(
image: RgbImage, image: RgbImage,
options: Partial<DenoiseOptions>, options: Partial<DenoiseOptions>,
runBase: BaseDenoiser, runBase: BaseDenoiser,
onStage?: (stage: DenoiseStage) => void,
): Promise<DenoiseOutput> { ): Promise<DenoiseOutput> {
const opts: DenoiseOptions = { ...DEFAULT_OPTIONS, ...options, gate: { ...DEFAULT_GATE, ...options.gate } }; const opts: DenoiseOptions = { ...DEFAULT_OPTIONS, ...options, gate: { ...DEFAULT_GATE, ...options.gate } };
const started = now(); const started = now();
@@ -193,6 +201,7 @@ export async function denoiseRgb(
const { y, cb, cr } = toYcc(image); const { y, cb, cr } = toYcc(image);
let mark = now(); let mark = now();
onStage?.('analyse');
const noise: NoiseModel = estimateNoise(y, width, height); const noise: NoiseModel = estimateNoise(y, width, height);
const timings: StageTimings = { const timings: StageTimings = {
noise: now() - mark, noise: now() - mark,
@@ -231,6 +240,7 @@ export async function denoiseRgb(
const decimatedSigma = const decimatedSigma =
backscale > 1.001 ? (prefilterWidth - 1 / 3) / (prefilterWidth * prefilterWidth) : 1; backscale > 1.001 ? (prefilterWidth - 1 / 3) / (prefilterWidth * prefilterWidth) : 1;
const baseSigma = noise.sigmaAt(110) * decimatedSigma; const baseSigma = noise.sigmaAt(110) * decimatedSigma;
onStage?.('base');
const baseOut = await runBase(baseInput, baseSigma); const baseOut = await runBase(baseInput, baseSigma);
const baseUp = toYcc(upsampleBase(baseOut, width, height)); const baseUp = toYcc(upsampleBase(baseOut, width, height));
timings.base = now() - mark; timings.base = now() - mark;
@@ -266,6 +276,7 @@ export async function denoiseRgb(
timings.structure = now() - mark; timings.structure = now() - mark;
mark = now(); mark = now();
onStage?.('gate');
let gate = detailGate(detail, width, height, sigmaMap, coherence, opts.gate); let gate = detailGate(detail, width, height, sigmaMap, coherence, opts.gate);
// Second, coarser band: `smooth2 - smooth6` is a band-pass around 3-8 px. It // Second, coarser band: `smooth2 - smooth6` is a band-pass around 3-8 px. It
@@ -292,6 +303,7 @@ export async function denoiseRgb(
const autoGate = opts.cleanSigma > 0 ? smoothstep(0.8, opts.cleanSigma, noise.global) : 1; const autoGate = opts.cleanSigma > 0 ? smoothstep(0.8, opts.cleanSigma, noise.global) : 1;
const amount = clamp01(opts.amount) * autoGate; const amount = clamp01(opts.amount) * autoGate;
onStage?.('render');
const outY = new Float32Array(pixels); const outY = new Float32Array(pixels);
const outCb = new Float32Array(pixels); const outCb = new Float32Array(pixels);
const outCr = new Float32Array(pixels); const outCr = new Float32Array(pixels);
Binary file not shown.
Binary file not shown.
+282
View File
@@ -0,0 +1,282 @@
/**
* Server HTTP integration tests.
*
* The real server is started once against a throwaway data directory, so these
* exercise the routing, session, ownership, quota, gallery and file-serving
* layers that the pure-logic suite cannot reach. Nothing touches a real catalog.
*/
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const PORT = 18_000 + Math.floor(Math.random() * 20_000);
const BASE = `http://127.0.0.1:${PORT}`;
let child = null;
let dataDir = '';
let output = '';
/** One browser: keeps the cookies the server sets for this session. */
class Client {
cookies = new Map();
async call(pathname, init = {}) {
const headers = { ...(init.headers ?? {}) };
if (this.cookies.size) {
headers.cookie = [...this.cookies].map(([key, value]) => `${key}=${value}`).join('; ');
}
const res = await fetch(BASE + pathname, { ...init, headers });
for (const raw of res.headers.getSetCookie?.() ?? []) {
const [pair] = raw.split(';');
const at = pair.indexOf('=');
const key = pair.slice(0, at).trim();
const value = pair.slice(at + 1).trim();
if (!value || /Max-Age=0/i.test(raw)) this.cookies.delete(key);
else this.cookies.set(key, value);
}
return res;
}
async json(pathname, init = {}) {
const res = await this.call(pathname, init);
const text = await res.text();
let body = null;
try {
body = text ? JSON.parse(text) : null;
} catch {
body = { raw: text };
}
return { res, body };
}
}
const postJson = (payload) => ({
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
});
const putJson = (payload) => ({ ...postJson(payload), method: 'PUT' });
const admin = new Client();
const member = new Client();
const guest = new Client();
const eventId = 'evt-http-test';
const photoId = 'ph-http-test';
const photoBytes = Buffer.alloc(8 * 1024, 7);
function photoRecord(extra = {}) {
return {
id: photoId,
eventId,
name: 'audit.jpg',
width: 100,
height: 80,
size: 2,
mime: 'image/jpeg',
addedAt: Date.now(),
edits: {},
history: [],
rating: 0,
flag: 'none',
keywords: [],
thumb: '',
...extra,
};
}
beforeAll(async () => {
dataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'luminary-http-'));
child = spawn(process.execPath, ['server/index.mjs'], {
cwd: ROOT,
env: {
...process.env,
LUMINARY_DATA: dataDir,
PORT: String(PORT),
HOST: '127.0.0.1',
LUMINARY_LOCAL: '',
LUMINARY_INVITE: '',
},
stdio: ['ignore', 'pipe', 'pipe'],
});
child.stdout.on('data', (chunk) => {
output += chunk;
});
child.stderr.on('data', (chunk) => {
output += chunk;
});
const deadline = Date.now() + 30_000;
while (Date.now() < deadline) {
try {
const res = await fetch(`${BASE}/api/health`);
if (res.ok) return;
} catch {
/* not listening yet */
}
await new Promise((resolve) => setTimeout(resolve, 150));
}
throw new Error(`server did not start\n${output}`);
}, 45_000);
afterAll(async () => {
child?.kill('SIGKILL');
if (dataDir) await fsp.rm(dataDir, { recursive: true, force: true }).catch(() => undefined);
});
describe('auth and ownership', () => {
test('the first account is the admin and gets a session', async () => {
const { res, body } = await admin.json(
'/api/auth/register',
postJson({ email: 'Admin@Example.com', password: 'password123', name: 'Admin' }),
);
expect(res.status).toBe(201);
expect(body.user.role).toBe('admin');
const me = await admin.json('/api/auth/me');
expect(me.res.status).toBe(200);
expect(me.body.user.email).toBe('admin@example.com');
});
test('registration is closed once an account exists', async () => {
const { res } = await guest.json(
'/api/auth/register',
postJson({ email: 'walk-in@example.com', password: 'password123' }),
);
expect(res.status).toBe(403);
});
test('an invited member cannot reach another owner\'s photo', async () => {
const invite = await admin.json(
'/api/admin/invites',
postJson({ email: 'member@example.com', role: 'member' }),
);
expect(invite.res.status).toBe(201);
const registered = await member.json(
'/api/auth/register',
postJson({
email: 'member@example.com',
password: 'password123',
inviteToken: invite.body.invite.token,
}),
);
expect(registered.res.status).toBe(201);
expect(registered.body.user.role).toBe('member');
const upload = await admin.call(`/api/photos/${photoId}/original?name=audit.jpg&mime=image/jpeg`, {
method: 'POST',
headers: { 'content-type': 'application/octet-stream' },
body: photoBytes,
});
expect(upload.status).toBe(201);
});
test('a saved record cannot shrink its measured size', async () => {
const saved = await admin.json(`/api/photos/${photoId}`, putJson(photoRecord()));
expect(saved.res.status).toBe(200);
const quota = await admin.json('/api/quota');
expect(quota.res.status).toBe(200);
expect(quota.body.used).toBe(photoBytes.length);
});
test('a member cannot read or overwrite the admin\'s photo', async () => {
const preview = await member.call(`/api/photos/${photoId}/preview`);
expect(preview.status).toBe(404);
const overwrite = await member.call(`/api/photos/${photoId}`, putJson({ ...photoRecord(), name: 'stolen.jpg' }));
expect(overwrite.status).toBe(404);
});
test('a member cannot park a photo inside another owner\'s event', async () => {
const event = await admin.call(`/api/events/${eventId}`, putJson({ id: eventId, name: 'Audit shoot', createdAt: Date.now() }));
expect(event.status).toBe(200);
const sneaky = await member.call('/api/photos/ph-member-1', putJson(photoRecord({ id: 'ph-member-1' })));
expect(sneaky.status).toBe(404);
});
});
describe('file serving', () => {
test('byte ranges resume a download', async () => {
const res = await admin.call(`/api/photos/${photoId}/original`, {
headers: { range: 'bytes=100-199' },
});
expect(res.status).toBe(206);
expect(res.headers.get('content-range')).toBe(`bytes 100-199/${photoBytes.length}`);
expect(res.headers.get('accept-ranges')).toBe('bytes');
const body = Buffer.from(await res.arrayBuffer());
expect(body.equals(photoBytes.subarray(100, 200))).toBe(true);
});
test('an impossible range is refused without touching other requests', async () => {
const res = await admin.call(`/api/photos/${photoId}/original`, {
headers: { range: `bytes=${photoBytes.length + 10}-` },
});
expect(res.status).toBe(416);
const health = await fetch(`${BASE}/api/health`);
expect(health.status).toBe(200);
});
test('an unreadable original answers 404 and leaves the server running', async () => {
if (process.getuid?.() === 0) return; // root ignores file permissions
const original = path.join(dataDir, 'originals', `${photoId}.jpg`);
fs.chmodSync(original, 0o000);
try {
const res = await admin.call(`/api/photos/${photoId}/original`);
expect(res.status).toBe(404);
const health = await fetch(`${BASE}/api/health`);
expect(health.status).toBe(200);
} finally {
fs.chmodSync(original, 0o644);
}
});
});
describe('proofing gallery', () => {
test('downloads count against the cap only when a file is sent', async () => {
const share = await admin.json(`/api/events/${eventId}/share`, { method: 'POST' });
expect(share.res.status).toBe(200);
const token = share.body.token;
const settings = await admin.call(
`/api/events/${eventId}/share/settings`,
putJson({ allowDownloads: true, downloadCap: 2 }),
);
expect(settings.status).toBe(200);
const pick = await guest.call(
`/api/galleries/${token}/picks`,
postJson({ photoId, clientId: 'client-1', clientName: 'Client', picked: true }),
);
expect(pick.status).toBe(200);
// First download uses one of the two allowed downloads.
const first = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
expect(first.status).toBe(200);
await first.arrayBuffer();
// A missing render must not consume the remaining allowance.
const original = path.join(dataDir, 'originals', `${photoId}.jpg`);
// Outside originals/: any `<id>.*` name inside that folder is still an original.
const parked = path.join(dataDir, `${photoId}.jpg.parked`);
await fsp.rename(original, parked);
const missing = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
expect(missing.status).toBe(404);
await fsp.rename(parked, original);
const second = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
expect(second.status).toBe(200);
await second.arrayBuffer();
const third = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
expect(third.status).toBe(403);
});
});
+40 -1
View File
@@ -119,7 +119,38 @@ export function resizeRgb16(rgb16, width, height, tw, th) {
* client would have to guess the conversion, and a self-describing sidecar also * client would have to guess the conversion, and a self-describing sidecar also
* keeps working for imports that predate a catalogue migration. * keeps working for imports that predate a catalogue migration.
*/ */
/**
* Deflate settings for the 16-bit sidecar. RLE wins here because the rows are
* Sub-filtered first: a photographic row turns into mostly small byte
* differences, and run-length coding stores them in a few bits each. On a
* 40 MP sidecar this took compression from 2.87 s to 1.10 s and the file from
* 58.47 MB to 58.06 MB; the decoded samples are byte-identical.
*/
const SIDECAR_DEFLATE = { level: 6, strategy: zlib.constants.Z_RLE };
export function encodePng16(rgb16, width, height, matrix = null) { export function encodePng16(rgb16, width, height, matrix = null) {
const raw = png16Rows(rgb16, width, height);
return png16File(zlib.deflateSync(raw, SIDECAR_DEFLATE), width, height, matrix);
}
/**
* The same PNG, with the deflate handed to libuv's thread pool.
*
* A 40 MP sidecar is ~110 MB and takes about five seconds to compress. Run
* synchronously that stalls the entire server for the duration, so four
* parallel imports finished one after another while the event loop was busy;
* the import felt frozen and preview requests queued behind it.
*/
export async function encodePng16Async(rgb16, width, height, matrix = null) {
const raw = png16Rows(rgb16, width, height);
const idat = await new Promise((resolve, reject) => {
zlib.deflate(raw, SIDECAR_DEFLATE, (err, out) => (err ? reject(err) : resolve(out)));
});
return png16File(idat, width, height, matrix);
}
/** Sub-filtered rows: each byte minus the byte six to its left. */
function png16Rows(rgb16, width, height) {
const stride = width * 6; const stride = width * 6;
const raw = Buffer.alloc((stride + 1) * height); const raw = Buffer.alloc((stride + 1) * height);
const row = Buffer.alloc(stride); const row = Buffer.alloc(stride);
@@ -134,7 +165,10 @@ export function encodePng16(rgb16, width, height, matrix = null) {
raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff; raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff;
} }
} }
const idat = zlib.deflateSync(raw, { level: 6 }); return raw;
}
function png16File(idat, width, height, matrix = null) {
const ihdr = Buffer.alloc(13); const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0); ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4); ihdr.writeUInt32BE(height, 4);
@@ -199,7 +233,12 @@ export async function cameraThumb16(png16, width, height, matrix = null) {
const sharp = await loadSharp(); const sharp = await loadSharp();
if (!sharp || width < 1 || height < 1) return null; if (!sharp || width < 1 || height < 1) return null;
try { try {
// `depth: 'ushort'` on the output only sets the container: without asking
// for the rgb16 colourspace, libvips runs the resize on 8-bit pixels and the
// samples come back as their high bytes alone (7 instead of 2000), which
// renders as a near-black tile.
const { data, info } = await sharp(png16) const { data, info } = await sharp(png16)
.toColourspace('rgb16')
.resize({ width, height, fit: 'fill' }) .resize({ width, height, fit: 'fill' })
.raw({ depth: 'ushort' }) .raw({ depth: 'ushort' })
.toBuffer({ resolveWithObject: true }); .toBuffer({ resolveWithObject: true });
+14
View File
@@ -1,3 +1,4 @@
import sharp from 'sharp';
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { cameraThumb16, encodePng16, png16Matrix, resizeRgb16 } from './imaging.mjs'; import { cameraThumb16, encodePng16, png16Matrix, resizeRgb16 } from './imaging.mjs';
@@ -75,6 +76,19 @@ describe('cameraThumb16', () => {
expect(out[25]).toBe(2); // colour type RGB expect(out[25]).toBe(2); // colour type RGB
}); });
it('keeps the full 16-bit samples, not just their high bytes', async () => {
// sharp's raw output is 8-bit unless the pipeline is asked for rgb16, and a
// downconverted thumbnail decodes to 7/15/23 instead of 2000/4000/6000.
const source = encodePng16(flat16(4, 2, [2000, 4000, 6000]), 4, 2, MATRIX);
const out = await cameraThumb16(source, 2, 1);
const { data } = await sharp(out)
.toColourspace('rgb16')
.raw({ depth: 'ushort' })
.toBuffer({ resolveWithObject: true });
const samples = [0, 2, 4].map((at) => data.readUInt16LE(at));
expect(samples).toEqual([2000, 4000, 6000]);
});
it('keeps the camera matrix so the client can convert the samples', async () => { it('keeps the camera matrix so the client can convert the samples', async () => {
const source = encodePng16(flat16(4, 2, [1000, 2000, 3000]), 4, 2, MATRIX); const source = encodePng16(flat16(4, 2, [1000, 2000, 3000]), 4, 2, MATRIX);
const out = await cameraThumb16(source, 2, 1); const out = await cameraThumb16(source, 2, 1);
+192 -27
View File
@@ -58,6 +58,7 @@ import {
import { import {
defaultRoot, defaultRoot,
findOriginal, findOriginal,
findOriginals,
findPreview, findPreview,
findPreview16, findPreview16,
findProof, findProof,
@@ -126,7 +127,27 @@ import {
startImmichImport, startImmichImport,
} from './immich.mjs'; } from './immich.mjs';
const VERSION = '0.5.1'; /**
* The version is read from package.json rather than repeated here, so a release
* cannot report one version and ship another. Every bundle ships that file next
* to `server/`: the Docker image, the Linux and Windows bundles, and the macOS
* app all copy it alongside the source tree.
*/
function readVersion() {
const file = new URL('../package.json', import.meta.url);
let version;
try {
version = JSON.parse(fs.readFileSync(file, 'utf8')).version;
} catch (error) {
throw new Error(`server: cannot read the version from ${file.pathname}: ${error.message}`);
}
if (typeof version !== 'string' || !version) {
throw new Error(`server: ${file.pathname} has no "version"`);
}
return version;
}
const VERSION = readVersion();
const COOKIE = 'lumen_session'; const COOKIE = 'lumen_session';
/** Self-only policy; must allow the wasm engines and React inline styles. */ /** Self-only policy; must allow the wasm engines and React inline styles. */
@@ -531,7 +552,13 @@ function match(pathname, pattern) {
const params = {}; const params = {};
for (let i = 0; i < p.length; i++) { for (let i = 0; i < p.length; i++) {
if (p[i].startsWith(':')) { if (p[i].startsWith(':')) {
params[p[i].slice(1)] = decodeURIComponent(a[i]); // A malformed escape such as %E0%A4%A must not throw URIError out of the
// router; it simply cannot match any record.
try {
params[p[i].slice(1)] = decodeURIComponent(a[i]);
} catch {
return null;
}
} else if (p[i] !== a[i]) { } else if (p[i] !== a[i]) {
return null; return null;
} }
@@ -539,6 +566,40 @@ function match(pathname, pattern) {
return params; return params;
} }
/** `bytes=start-end` / `bytes=start-` / `bytes=-suffix`, first range only. */
function parseRange(header, size) {
if (typeof header !== 'string' || !header.startsWith('bytes=')) return null;
const spec = header.slice(6).split(',')[0].trim();
const match = /^(\d*)-(\d*)$/.exec(spec);
if (!match) return null;
const [, rawStart, rawEnd] = match;
if (!rawStart && !rawEnd) return null;
let start;
let end;
if (!rawStart) {
const suffix = Number(rawEnd);
if (!Number.isFinite(suffix) || suffix <= 0) return { unsatisfiable: true };
start = Math.max(0, size - suffix);
end = size - 1;
} else {
start = Number(rawStart);
end = rawEnd ? Number(rawEnd) : size - 1;
if (end >= size) end = size - 1;
}
if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= size) {
return { unsatisfiable: true };
}
return { start, end };
}
/** The precompressed variant the client can take, if this build wrote one. */
function acceptedEncoding(req) {
const value = String(req.headers['accept-encoding'] ?? '').toLowerCase();
if (value.includes('br')) return 'br';
if (value.includes('gzip')) return 'gzip';
return null;
}
function sendBuffer(res, data, type, cache = 'private, max-age=3600') { function sendBuffer(res, data, type, cache = 'private, max-age=3600') {
res.writeHead(200, { res.writeHead(200, {
'Content-Type': type, 'Content-Type': type,
@@ -561,19 +622,59 @@ function bridgeLinkForPhoto(photoId) {
async function sendFile(req, res, filePath, type, cache = 'private, max-age=86400', extraHeaders = {}) { async function sendFile(req, res, filePath, type, cache = 'private, max-age=86400', extraHeaders = {}) {
if (!filePath) return error(res, 404, 'Not found'); if (!filePath) return error(res, 404, 'Not found');
// Open first, then stat the open handle. A file can vanish or lose its
// permissions between a separate stat and open, and a ReadStream error with
// no listener is an uncaught exception that takes the whole server down.
let handle;
try { try {
const stat = await fsp.stat(filePath); handle = await fsp.open(filePath, 'r');
res.writeHead(200, { } catch {
return error(res, 404, 'Not found');
}
try {
const stat = await handle.stat();
// Byte ranges let a 300 MB original resume after a dropped connection
// instead of starting over. The whole file is still streamed, never read
// into memory.
const range = req.method === 'GET' ? parseRange(req.headers.range, stat.size) : null;
if (range?.unsatisfiable) {
await handle.close();
res.writeHead(416, {
'Content-Range': `bytes */${stat.size}`,
'Accept-Ranges': 'bytes',
'Cache-Control': cache,
'X-Content-Type-Options': 'nosniff',
});
return res.end();
}
const start = range ? range.start : 0;
const end = range ? range.end : stat.size - 1;
const length = stat.size === 0 ? 0 : end - start + 1;
const headers = {
'Content-Type': type, 'Content-Type': type,
'Content-Length': stat.size, 'Content-Length': length,
'Cache-Control': cache, 'Cache-Control': cache,
'X-Content-Type-Options': 'nosniff', 'X-Content-Type-Options': 'nosniff',
'Accept-Ranges': 'bytes',
...extraHeaders, ...extraHeaders,
}); };
if (req.method === 'HEAD') return res.end(); if (range) headers['Content-Range'] = `bytes ${start}-${end}/${stat.size}`;
fs.createReadStream(filePath).pipe(res); res.writeHead(range ? 206 : 200, headers);
if (req.method === 'HEAD' || length === 0) {
await handle.close();
return res.end();
}
const stream = range ? handle.createReadStream({ start, end }) : handle.createReadStream();
// A read that fails mid-transfer (unmounted volume, I/O error) cannot be
// turned into an error page once the 200 is on the wire, but it must not
// crash the process either.
stream.on('error', () => res.destroy());
res.on('close', () => stream.destroy());
return stream.pipe(res);
} catch { } catch {
error(res, 404, 'Not found'); await handle.close().catch(() => undefined);
if (!res.headersSent) return error(res, 404, 'Not found');
return res.destroy();
} }
} }
@@ -1765,9 +1866,12 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
if (!hit) return error(res, 404, 'Not found'); if (!hit) return error(res, 404, 'Not found');
const proof = findProof(params.id); const proof = findProof(params.id);
const file = proof ?? findPreview(params.id) ?? findOriginal(params.id); const file = proof ?? findPreview(params.id) ?? findOriginal(params.id);
if (!file) return error(res, 404, 'Not found');
const originalName = String(hit.photo.name || 'photo.jpg'); const originalName = String(hit.photo.name || 'photo.jpg');
const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-'); const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-');
const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name); const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name);
// Count the download only once there is a file to send, so a missing render
// does not quietly use up the client's allowance.
noteGalleryDownload(params.token); noteGalleryDownload(params.token);
return sendFile(req, res, file, mime, 'private, max-age=3600', { return sendFile(req, res, file, mime, 'private, max-age=3600', {
'Content-Disposition': `attachment; filename="${safe}"`, 'Content-Disposition': `attachment; filename="${safe}"`,
@@ -2078,6 +2182,10 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
const url = new URL(req.url ?? '/', 'http://localhost'); const url = new URL(req.url ?? '/', 'http://localhost');
const name = url.searchParams.get('name') || 'upload'; const name = url.searchParams.get('name') || 'upload';
const drop = url.searchParams.get('drop') === '1'; const drop = url.searchParams.get('drop') === '1';
// The import dialog can ask for an 8-bit import; anything else keeps the
// LUMINARY_16BIT setting. Only `sidecar=0` is meaningful, so the default path
// behaves exactly as before.
const sidecar = url.searchParams.get('sidecar') !== '0';
const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name); const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name);
const ext = (name.split('.').pop() || 'bin').toLowerCase(); const ext = (name.split('.').pop() || 'bin').toLowerCase();
// TIFF is not a raw container, but browsers cannot decode it either. It takes // TIFF is not a raw container, but browsers cannot decode it either. It takes
@@ -2088,18 +2196,32 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
// New ids are part of the normal import flow: the client uploads bytes first // New ids are part of the normal import flow: the client uploads bytes first
// and PUTs the record afterwards. Until that row exists the bytes are charged // and PUTs the record afterwards. Until that row exists the bytes are charged
// to this user's quota, so nobody can fill the disk with unclaimed files. // to this user's quota, so nobody can fill the disk with unclaimed files.
const limit = owner // An existing photo may still be replaced, but the replacement only has the
? MAX_UPLOAD // room its own file frees plus what is left of the quota: an account that is
: Math.min(MAX_UPLOAD, Math.max(0, quotaState(user.id).remaining - pendingBytes(user.id))); // already full can shrink an original, never grow one past its cap.
const replacing = owner !== null ? findOriginal(params.id) : null;
const replacedBytes = replacing
? ((await fsp.stat(replacing).catch(() => null))?.size ?? 0)
: 0;
const limit = Math.min(
MAX_UPLOAD,
Math.max(0, quotaState(user.id).remaining + replacedBytes - pendingBytes(user.id)),
);
if (limit < 1) { if (limit < 1) {
return error(res, 413, 'This account has no storage quota left for a new upload'); return error(
res,
413,
owner
? 'This account has no storage quota left for this file'
: 'This account has no storage quota left for a new upload',
);
} }
const announced = Number(req.headers['content-length']); const announced = Number(req.headers['content-length']);
if (Number.isFinite(announced) && announced > limit) { if (Number.isFinite(announced) && announced > limit) {
return error( return error(
res, res,
413, 413,
owner announced > MAX_UPLOAD
? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit` ? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit`
: 'This upload does not fit in the remaining storage quota', : 'This upload does not fit in the remaining storage quota',
); );
@@ -2117,8 +2239,6 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
} }
const target = originalTarget(params.id, ext); const target = originalTarget(params.id, ext);
const previous = findOriginal(params.id);
if (previous) await fsp.rm(previous, { force: true }).catch(() => undefined);
let size = 0; let size = 0;
try { try {
@@ -2129,7 +2249,7 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
return error( return error(
res, res,
413, 413,
owner limit >= MAX_UPLOAD
? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit` ? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit`
: 'This upload does not fit in the remaining storage quota', : 'This upload does not fit in the remaining storage quota',
); );
@@ -2141,6 +2261,15 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
return error(res, 400, 'Empty upload'); return error(res, 400, 'Empty upload');
} }
// Replace the previous bytes only now that the new file is safely on disk: a
// failed or aborted replacement must leave the photo it was replacing
// readable. Other extensions are dropped too, so an id never keeps a stale
// copy that `findOriginal` might return instead of the new file.
for (const previous of findOriginals(params.id)) {
if (previous === target) continue;
await fsp.rm(previous, { force: true }).catch(() => undefined);
}
recentUploads.set(params.id, { recentUploads.set(params.id, {
ownerId: user.id, ownerId: user.id,
bytes: size, bytes: size,
@@ -2151,7 +2280,7 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
if (raw) { if (raw) {
try { try {
const data = await fsp.readFile(target); const data = await fsp.readFile(target);
const decoded = still ? await decodeStill(data) : await decodeRaw(data); const decoded = still ? await decodeStill(data) : await decodeRaw(data, { sidecar });
await writePreview(params.id, decoded.jpeg, decoded.ext); await writePreview(params.id, decoded.jpeg, decoded.ext);
if (decoded.preview16) { if (decoded.preview16) {
await writePreview16(params.id, decoded.preview16.data); await writePreview16(params.id, decoded.preview16.data);
@@ -2370,10 +2499,14 @@ route('POST', '/api/photos/:id/denoise', async ({ req, res, params }) => {
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found');
// Denoise the proxy the editor actually shows, not the raw: the result has to // Denoise the proxy the editor actually shows, not the raw: the result has to
// line up pixel for pixel with the canvas and with the client's export path. // line up pixel for pixel with the canvas and with the client's export path.
// The Amount slider is the client's: the render is always full strength. // The Amount slider is the client's: the render is always full strength. The
// base denoiser (guided / nlm / scunet) is chosen here and folded into the
// cache key, so each model renders to its own asset.
const source = findPreview(params.id) ?? findOriginal(params.id); const source = findPreview(params.id) ?? findOriginal(params.id);
if (!source) return error(res, 404, 'Nothing to denoise'); if (!source) return error(res, 404, 'Nothing to denoise');
const job = startDenoise({ photoId: params.id, sourcePath: source }); const body = await readJson(req).catch(() => ({}));
const base = body?.base === 'nlm' || body?.base === 'scunet' ? body.base : 'guided';
const job = startDenoise({ photoId: params.id, sourcePath: source, base });
return json(res, 202, { jobId: job.id, state: job.state }); return json(res, 202, { jobId: job.id, state: job.state });
}); });
@@ -2391,6 +2524,12 @@ route('GET', '/api/denoise/jobs/:id', async ({ req, res, params }) => {
error: job.error ?? null, error: job.error ?? null,
url: job.url ?? null, url: job.url ?? null,
stats: job.stats ?? null, stats: job.stats ?? null,
// Where a long run is, so the panel can name the stage instead of showing a
// spinner with no truth in it.
progress: job.progress ?? null,
// Without this the panel cannot tell a reused render from a fresh one and
// reports "Denoise ready" for both.
cached: Boolean(job.cached),
}); });
}); });
@@ -2458,6 +2597,13 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL'); if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL');
const record = { ...body, id: params.id }; const record = { ...body, id: params.id };
// A photo may only join an event in the same workspace; otherwise a member
// could park rows inside someone else's event and skew its totals.
const targetEventId = typeof record.eventId === 'string' ? record.eventId : '';
if (targetEventId && !ownedBy(eventOwner(targetEventId), user)) {
return error(res, 404, 'No such event');
}
// Quota accounting uses bytes the server actually received, not the client's // Quota accounting uses bytes the server actually received, not the client's
// claim, for an upload that just finished. // claim, for an upload that just finished.
const upload = recentUploads.get(params.id); const upload = recentUploads.get(params.id);
@@ -2467,6 +2613,16 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
} }
record.mime = record.raw ? 'image/jpeg' : normalizePhotoMime(record.mime, record.name); record.mime = record.raw ? 'image/jpeg' : normalizePhotoMime(record.mime, record.name);
// Library totals, quota usage and prune plans are measured from the bytes on
// disk, not from what a saved record claims. Without this a client could PUT
// size: 2 for a 20 MB original, shrink its reported usage and dodge its quota
// while the file stayed on the volume.
const storedOriginal = findOriginal(params.id);
if (storedOriginal) {
const stat = await fsp.stat(storedOriginal).catch(() => null);
if (stat) record.size = stat.size;
}
const thumb = decodeDataUrl(record.thumb); const thumb = decodeDataUrl(record.thumb);
if (thumb) { if (thumb) {
await writeThumb(params.id, thumb.data); await writeThumb(params.id, thumb.data);
@@ -2543,13 +2699,22 @@ async function serveStatic(req, res, url) {
if (stat.isFile()) { if (stat.isFile()) {
const ext = path.extname(candidate).toLowerCase(); const ext = path.extname(candidate).toLowerCase();
const immutable = pathname.startsWith('/assets/'); const immutable = pathname.startsWith('/assets/');
return sendFile( const cache = immutable ? 'public, max-age=31536000, immutable' : 'no-cache';
req, const mime = MIME[ext] ?? 'application/octet-stream';
res, // `npm run build` writes .br/.gz copies of the text assets, so the
candidate, // first request does not pay for compression and every later one is
MIME[ext] ?? 'application/octet-stream', // just a file read.
immutable ? 'public, max-age=31536000, immutable' : 'no-cache', const encoding = acceptedEncoding(req);
); const variants = encoding === 'br' ? ['br', 'gz'] : encoding === 'gzip' ? ['gz'] : [];
for (const variant of variants) {
const packed = `${candidate}.${variant}`;
if (!fs.existsSync(packed)) continue;
return sendFile(req, res, packed, mime, cache, {
'Content-Encoding': variant === 'br' ? 'br' : 'gzip',
Vary: 'Accept-Encoding',
});
}
return sendFile(req, res, candidate, mime, cache);
} }
} catch { } catch {
/* fall through to the SPA entry */ /* fall through to the SPA entry */
+26 -3
View File
@@ -88,17 +88,40 @@ class LibRawPool {
} }
} }
/** Run `fn` with a decoder instance; the instance returns to the pool after. */ /**
async use(fn) { * Run `fn` with a decoder instance; the instance returns to the pool after.
*
* `timeoutMs` covers only the work, never the wait for a free worker: a job
* that sat in the queue is not slow, and timing it from the call site made
* parallel imports fail in waves. A timed-out worker is still chewing on the
* abandoned job, so it is destroyed rather than handed to the next caller.
*/
async use(fn, { timeoutMs = 0, label = 'LibRaw' } = {}) {
const lib = await this.acquire(); const lib = await this.acquire();
let healthy = true; let healthy = true;
let timer = null;
try { try {
return await fn(lib); if (!timeoutMs) return await fn(lib);
const guard = new Promise((_, reject) => {
timer = setTimeout(
() => reject(new Error(`${label} timed out on this file`)),
timeoutMs,
);
});
try {
return await Promise.race([fn(lib), guard]);
} catch (err) {
if (timer && /timed out/.test(String(err?.message ?? '')) && err instanceof Error) {
healthy = false;
}
throw err;
}
} catch (err) { } catch (err) {
// A dead worker keeps failing, so recycle it instead of handing it back. // A dead worker keeps failing, so recycle it instead of handing it back.
if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false; if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false;
throw err; throw err;
} finally { } finally {
if (timer) clearTimeout(timer);
this.release(lib, healthy); this.release(lib, healthy);
} }
} }
+135 -67
View File
@@ -1,6 +1,14 @@
import { RAW_16BIT, RAW_PREVIEW_EDGE } from './config.mjs'; import { RAW_16BIT, RAW_PREVIEW_EDGE, RAW_TIMEOUT_MS, RAW_XTRANS_QUALITY } from './config.mjs';
import { cameraToProxy, readRgbCam } from './color.mjs'; import { readRgbCam } from './color.mjs';
import { encodePng16, encodeRgb, jpegInfo, loadSharp, resizeRgb16, toJpegProxy } from './imaging.mjs'; import { cameraToProxyAsync } from './color-offload.mjs';
import {
encodePng16Async,
encodeRgb,
jpegInfo,
loadSharp,
resizeRgb16,
toJpegProxy,
} from './imaging.mjs';
import { loadLibRaw, rawPool } from './libraw-pool.mjs'; import { loadLibRaw, rawPool } from './libraw-pool.mjs';
/** Every raw container the pipeline will attempt, grouped by vendor family. */ /** Every raw container the pipeline will attempt, grouped by vendor family. */
@@ -39,15 +47,6 @@ export function isStillName(name = '') {
return SERVER_IMAGE_EXTENSIONS.has(ext); return SERVER_IMAGE_EXTENSIONS.has(ext);
} }
/** Rejects instead of waiting forever when a decoder wedges on one file. */
function withTimeout(promise, ms, message) {
let timer;
const guard = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(message)), ms);
});
return Promise.race([promise, guard]).finally(() => clearTimeout(timer));
}
/** True when the buffer starts with a container signature LibRaw can open. */ /** True when the buffer starts with a container signature LibRaw can open. */
export function looksLikeRaw(buffer) { export function looksLikeRaw(buffer) {
if (!buffer || buffer.length < 64) return false; if (!buffer || buffer.length < 64) return false;
@@ -146,11 +145,14 @@ function toRgb(img) {
); );
} }
const rgb = Buffer.alloc(pixelCount * 3); // Both outputs are shared memory: the camera-to-sRGB pass runs in a worker
// (color-offload.mjs) and writes these same bytes, so a 24 MP frame is not
// copied across the thread boundary.
const rgb = Buffer.from(new SharedArrayBuffer(pixelCount * 3));
let rgb16 = null; let rgb16 = null;
if (bits > 8) { if (bits > 8) {
const view = wide instanceof Uint16Array ? wide : src; const view = wide instanceof Uint16Array ? wide : src;
rgb16 = new Uint16Array(pixelCount * 3); rgb16 = new Uint16Array(new SharedArrayBuffer(pixelCount * 3 * 2));
for (let i = 0; i < pixelCount; i++) { for (let i = 0; i < pixelCount; i++) {
const s = i * colors; const s = i * colors;
const r = view[s]; const r = view[s];
@@ -182,91 +184,153 @@ function toRgb(img) {
* matrix metadata. A body LibRaw has no matrix for falls back to the plain sRGB * matrix metadata. A body LibRaw has no matrix for falls back to the plain sRGB
* decode, which is the same result the pipeline produced before. * decode, which is the same result the pipeline produced before.
*/ */
async function demosaic(buffer, cameraNative = true) { /**
* Fujifilm bodies that are *not* X-Trans: the Bayer-sensor GFX and X-A/T100/T200
* lines, plus the old FinePix compacts. Everyone else in the X series uses the
* 6x6 colour filter array.
*/
function isXTrans(make, model) {
if (!/fuji/i.test(String(make ?? ''))) return false;
const m = String(model ?? '').trim();
if (/^(gfx|finepix)/i.test(m)) return false;
if (/^x-(a\d|t100|t200)\b/i.test(m)) return false;
return /^x/i.test(m);
}
/**
* Demosaic one frame. On X-Trans the `userQual` setting counts Markesteijn
* passes, and LibRaw's 3-pass default is the single most expensive thing this
* pipeline does: 49.9 s on a 40 MP X-T5 frame here, against 8.8 s for one pass,
* which pushed every Fuji import into the decode timeout (and, under a parallel
* import, every file at once). The proxy is downsampled to RAW_PREVIEW_EDGE, so
* the extra passes were being thrown away by the resize anyway.
*
* The model is only known after the container is opened, and opening is ~0.2 s,
* so the file is re-opened with the cheaper setting rather than guessing from
* the filename.
*/
async function demosaic(buffer, { cameraNative = true } = {}) {
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed'); if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
return rawPool.use(async (lib) => { return rawPool.use(
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it async (lib) => {
// a copy so the caller's bytes survive for the embedded-preview fallback. const settings = cameraNative
await lib.open( ? DECODE_SETTINGS
Buffer.from(buffer), : { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false };
cameraNative ? DECODE_SETTINGS : { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false }, // LibRaw transfers the buffer to its worker, which detaches it here. Hand it
); // a copy so the caller's bytes survive for the embedded-preview fallback.
const image = toRgb(await lib.imageData()); await lib.open(Buffer.from(buffer), settings);
const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null; if (settings.userQual > RAW_XTRANS_QUALITY) {
return { ...image, rgbCam }; const info = await lib.metadata();
}); if (isXTrans(info?.camera_make, info?.camera_model)) {
await lib.open(Buffer.from(buffer), { ...settings, userQual: RAW_XTRANS_QUALITY });
}
}
const image = toRgb(await lib.imageData());
const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null;
return { ...image, rgbCam };
},
{ timeoutMs: RAW_TIMEOUT_MS, label: 'LibRaw' },
);
} }
const SOI = Buffer.from([0xff, 0xd8, 0xff]); const SOI = Buffer.from([0xff, 0xd8, 0xff]);
const EOI = Buffer.from([0xff, 0xd9]); const EOI = Buffer.from([0xff, 0xd9]);
/** Pull the largest embedded JPEG straight out of a raw container. */ /**
export function extractEmbeddedJpeg(buffer) { * Every embedded JPEG in a raw container, largest first.
let best = null; *
let from = 0; * A single scan can land on a thumbnail's end-of-image and cut the file short:
while (from < buffer.length - 3) { * that produced a "preview" sharp refused to decode, which was then stored as a
const start = buffer.indexOf(SOI, from); * 0x0 JPEG. Callers walk the list and keep the first candidate that really
* decodes.
*/
export function extractEmbeddedJpegs(buffer) {
const starts = [];
let at = 0;
while (starts.length < 64) {
const start = buffer.indexOf(SOI, at);
if (start < 0) break; if (start < 0) break;
const end = buffer.indexOf(EOI, start + 3); starts.push(start);
if (end < 0) break; at = start + 3;
const length = end + 2 - start;
if (length > 4096 && (!best || length > best.length)) best = buffer.subarray(start, end + 2);
from = end + 2;
} }
return best; const found = [];
for (const start of starts) {
// Several end-of-image markers can follow one start: a preview that carries
// its own EXIF thumbnail ends twice. Take a few candidates per start and let
// the decoder pick, instead of committing to the first marker found.
let from = start + 3;
for (let attempt = 0; attempt < 3; attempt++) {
const end = buffer.indexOf(EOI, from);
if (end < 0) break;
if (end + 2 - start > 4096) found.push(buffer.subarray(start, end + 2));
from = end + 2;
}
}
return found.sort((a, b) => b.length - a.length);
} }
/** Camera preview, preferably the one LibRaw knows the offset and length of. */ /** The largest embedded JPEG, for callers that want one candidate. */
async function embeddedPreview(buffer) { export function extractEmbeddedJpeg(buffer) {
return extractEmbeddedJpegs(buffer)[0] ?? null;
}
/** Camera previews, best first: the one LibRaw knows about, then byte-scanned. */
async function embeddedPreviews(buffer) {
const candidates = [];
if ((await rawEngine()) === 'ready') { if ((await rawEngine()) === 'ready') {
try { try {
const thumb = await withTimeout( const thumb = await rawPool.use(
rawPool.use(async (lib) => { async (lib) => {
await lib.open(Buffer.from(buffer), { useCameraWb: true }); await lib.open(Buffer.from(buffer), { useCameraWb: true });
return lib.thumbnailData(); return lib.thumbnailData();
}), },
12000, { timeoutMs: 20000, label: 'LibRaw preview' },
'LibRaw preview timed out',
); );
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) { if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
return Buffer.from(thumb.data); candidates.push(Buffer.from(thumb.data));
} }
} catch { } catch {
/* fall through to the byte scan */ /* fall through to the byte scan */
} }
} }
return extractEmbeddedJpeg(buffer); candidates.push(...extractEmbeddedJpegs(buffer));
return candidates;
} }
/** /**
* Convert a raw file into an editable JPEG. LibRaw demosaics where possible and * Convert a raw file into an editable JPEG. LibRaw demosaics where possible and
* falls back to the camera's own embedded preview when it cannot. * falls back to the camera's own embedded preview when it cannot.
*
* `sidecar` writes the 16-bit samples beside the JPEG. It defaults to the
* server setting, and the import dialog can turn it off for one import: an
* 8-bit import decodes exactly the same, it just skips the second encode and the
* tens of megabytes of disk it costs.
*/ */
export async function decodeRaw(buffer) { export async function decodeRaw(buffer, { sidecar = RAW_16BIT } = {}) {
let librawError = null; let librawError = null;
if (looksLikeRaw(buffer)) { if (looksLikeRaw(buffer)) {
try { try {
let frame = await withTimeout(demosaic(buffer, true), 45000, 'LibRaw timed out on this file'); let frame = await demosaic(buffer, { cameraNative: true });
// No usable matrix (an odd body or older engine): decode the familiar sRGB // No usable matrix (an odd body or older engine): decode the familiar sRGB
// way instead of shipping camera samples nobody can convert. // way instead of shipping camera samples nobody can convert.
if (!frame.rgbCam || !frame.rgb16) frame = await withTimeout(demosaic(buffer, false), 45000, 'LibRaw timed out on this file'); if (!frame.rgbCam || !frame.rgb16) frame = await demosaic(buffer, { cameraNative: false });
const { width, height, rgbCam } = frame; const { width, height, rgbCam } = frame;
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and // Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
// `rgb16` the camera-native sidecar, sharing one white point. // `rgb16` the camera-native sidecar, sharing one white point.
if (rgbCam && frame.rgb16) cameraToProxy(frame.rgb16, frame.rgb, rgbCam); if (rgbCam && frame.rgb16) await cameraToProxyAsync(frame.rgb16, frame.rgb, rgbCam);
const { rgb } = frame; const { rgb } = frame;
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE); const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
// The sidecar must match the JPEG pixel for pixel: the editor swaps the // The sidecar must match the JPEG pixel for pixel: the editor swaps the
// two textures at the same uv, so a size disagreement would misalign the // two textures at the same uv, so a size disagreement would misalign the
// whole grade. It is optional -- encoding failures leave the JPEG path. // whole grade. It is optional -- encoding failures leave the JPEG path.
let preview16 = null; let preview16 = null;
if (frame.rgb16 && RAW_16BIT) { if (frame.rgb16 && sidecar) {
try { try {
const scaled = resizeRgb16(frame.rgb16, width, height, encoded.width, encoded.height); const scaled = resizeRgb16(frame.rgb16, width, height, encoded.width, encoded.height);
preview16 = { preview16 = {
// The matrix travels with the samples so the editor knows how to // The matrix travels with the samples so the editor knows how to
// turn camera RGB into sRGB without a second metadata fetch. // turn camera RGB into sRGB without a second metadata fetch.
data: encodePng16(scaled, encoded.width, encoded.height, rgbCam), data: await encodePng16Async(scaled, encoded.width, encoded.height, rgbCam),
width: encoded.width, width: encoded.width,
height: encoded.height, height: encoded.height,
rgbCam, rgbCam,
@@ -290,21 +354,25 @@ export async function decodeRaw(buffer) {
librawError = 'not a recognised raw container'; librawError = 'not a recognised raw container';
} }
const embedded = await embeddedPreview(buffer); // Keep the first candidate that sharp can actually decode. Never store bytes
if (embedded) { // that did not decode: a 0x0 "preview" is an unopenable photo in the catalog.
// A handful of candidates is enough; each rejected one costs a header parse,
// not a full decode.
for (const embedded of (await embeddedPreviews(buffer)).slice(0, 6)) {
const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE); const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE);
if (proxy) { if (!proxy) continue;
const size = await jpegInfo(proxy.data); const size = await jpegInfo(proxy.data);
return { const width = size?.width || proxy.width;
jpeg: proxy.data, const height = size?.height || proxy.height;
width: size?.width || proxy.width, if (!width || !height) continue;
height: size?.height || proxy.height, return {
engine: 'embedded', jpeg: proxy.data,
ext: proxy.ext, width,
note: `LibRaw could not decode this file (${librawError}); using the camera preview.`, height,
}; engine: 'embedded',
} ext: proxy.ext,
return { jpeg: embedded, width: 0, height: 0, engine: 'embedded', ext: 'jpg', note: librawError ?? undefined }; note: `LibRaw could not decode this file (${librawError}); using the camera preview.`,
};
} }
throw new Error( throw new Error(
+51
View File
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import { import {
RAW_EXTENSIONS, RAW_EXTENSIONS,
decodeRaw, decodeRaw,
extractEmbeddedJpegs,
decodeStill, decodeStill,
isRawName, isRawName,
isStillName, isStillName,
@@ -52,6 +53,56 @@ describe('raw format coverage', () => {
}); });
}); });
const JPEG_SOI = Buffer.from([0xff, 0xd8, 0xff]);
const JPEG_EOI = Buffer.from([0xff, 0xd9]);
/** A JPEG-shaped run of `total` bytes with no nested markers. */
function jpegBytes(total) {
return Buffer.concat([JPEG_SOI, Buffer.alloc(Math.max(1, total - 5), 0x11), JPEG_EOI]);
}
describe('embedded preview fallback', () => {
it('lists candidates largest first and ignores thumbnail-sized runs', () => {
const small = jpegBytes(9000);
const big = jpegBytes(90000);
const tiny = jpegBytes(1200);
const buffer = Buffer.concat([
Buffer.alloc(128),
small,
Buffer.alloc(32),
big,
Buffer.alloc(32),
tiny,
Buffer.alloc(32),
]);
const lengths = extractEmbeddedJpegs(buffer).map((jpeg) => jpeg.length);
// Splitting candidates at every end-of-image marker can yield over-long
// slices that span two images; those fail to decode and are skipped. What
// matters is that both real previews are offered, largest first, and that
// thumbnail-sized runs are not.
expect(lengths).toEqual([...lengths].sort((a, b) => b - a));
expect(lengths).toContain(big.length);
expect(lengths).toContain(small.length);
expect(lengths).not.toContain(tiny.length);
});
it('does not let a nested EXIF thumbnail truncate the full preview', () => {
// Regression: the scan used to stop at the thumbnail's end-of-image, so the
// "preview" it stored was a cut-off JPEG that sharp refused to decode and
// the import ended up as a 0x0 photo.
const thumb = jpegBytes(6000);
const outer = Buffer.concat([
JPEG_SOI,
Buffer.alloc(2000, 0x11),
thumb,
Buffer.alloc(40000, 0x11),
JPEG_EOI,
]);
const found = extractEmbeddedJpegs(Buffer.concat([Buffer.alloc(64), outer]));
expect(found[0].length).toBe(outer.length);
});
});
describe('TIFF decoding', () => { describe('TIFF decoding', () => {
it('turns a TIFF into a JPEG proxy', async () => { it('turns a TIFF into a JPEG proxy', async () => {
const { default: sharp } = await import('sharp'); const { default: sharp } = await import('sharp');
+21 -11
View File
@@ -88,15 +88,20 @@ export function originalTarget(id, ext = 'bin') {
return originalPath(id, ext); return originalPath(id, ext);
} }
export function findOriginal(id) { export function findOriginals(id) {
const safe = lookupId(id); const safe = lookupId(id);
if (!safe) return null; if (!safe) return [];
const { originals } = dirs(); const { originals } = dirs();
const prefix = `${safe}.`; const prefix = `${safe}.`;
for (const name of listFiles(originals)) { return listFiles(originals)
if (name.startsWith(prefix)) return path.join(originals, name); // An interrupted upload leaves `<id>.<ext>.part-xxxx` behind; it is not a
} // usable original, and returning it would serve a truncated image.
return null; .filter((name) => name.startsWith(prefix) && !name.includes('.part-'))
.map((name) => path.join(originals, name));
}
export function findOriginal(id) {
return findOriginals(id)[0] ?? null;
} }
export async function writePreview(id, data, ext = 'jpg') { export async function writePreview(id, data, ext = 'jpg') {
@@ -194,16 +199,21 @@ export function findDenoised(id, key) {
return path.join(dir, names[0]); return path.join(dir, names[0]);
} }
/** Remove every denoised render for a photo, sparing `keepKey` if given. */ /**
export function removeDenoised(id, keepKey) { * Remove denoised renders for a photo, sparing the keys named in `keepKeys`.
* A single key is accepted too; with none, every render for the photo goes.
*/
export function removeDenoised(id, keepKeys) {
const safe = lookupId(id); const safe = lookupId(id);
if (!safe) return 0; if (!safe) return 0;
const dir = path.join(storageRoot(), 'denoised'); const dir = path.join(storageRoot(), 'denoised');
const key = keepKey ? String(keepKey).replace(/[^a-z0-9]/gi, '') : null; const keys = (Array.isArray(keepKeys) ? keepKeys : keepKeys ? [keepKeys] : [])
const keep = key ? `${safe}.${key}.jpg` : null; .map((key) => String(key).replace(/[^a-z0-9]/gi, ''))
.filter(Boolean);
const keep = new Set(keys.map((key) => `${safe}.${key}.jpg`));
let removed = 0; let removed = 0;
for (const name of listFiles(dir)) { for (const name of listFiles(dir)) {
if (!name.startsWith(`${safe}.`) || name === keep) continue; if (!name.startsWith(`${safe}.`) || keep.has(name)) continue;
fs.rmSync(path.join(dir, name), { force: true }); fs.rmSync(path.join(dir, name), { force: true });
removed += 1; removed += 1;
} }
+127 -57
View File
@@ -1,21 +1,15 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import AboutModal from './components/AboutModal'; import AboutModal from './components/AboutModal';
import AdminPanel from './components/AdminPanel';
import CloudPanel from './components/CloudPanel'; import CloudPanel from './components/CloudPanel';
import CommandPalette from './components/CommandPalette'; import CommandPalette from './components/CommandPalette';
import ContextMenu, { type MenuEntry } from './components/ContextMenu'; import ContextMenu, { type MenuEntry } from './components/ContextMenu';
import Develop from './components/Develop'; import Develop from './components/Develop';
import EventSidebar from './components/EventSidebar'; import EventSidebar from './components/EventSidebar';
import ExportModal from './components/ExportModal'; import ExportModal from './components/ExportModal';
import CompareView from './components/CompareView';
import FilterBar from './components/FilterBar'; import FilterBar from './components/FilterBar';
import ImportModal from './components/ImportModal'; import ImportModal from './components/ImportModal';
import ImmichPanel from './components/ImmichPanel';
import LibraryGrid from './components/LibraryGrid'; import LibraryGrid from './components/LibraryGrid';
import MergeModal from './components/MergeModal';
import PasteSettingsModal from './components/PasteSettingsModal'; import PasteSettingsModal from './components/PasteSettingsModal';
import PrintModal from './components/PrintModal';
import ShareModal from './components/ShareModal';
import RawReprocessModal, { import RawReprocessModal, {
type RawReprocessFailure, type RawReprocessFailure,
type RawReprocessJob, type RawReprocessJob,
@@ -26,6 +20,15 @@ import Shortcuts from './components/Shortcuts';
import Stars, { ColorSwatches, FlagButtons } from './components/Stars'; import Stars, { ColorSwatches, FlagButtons } from './components/Stars';
import TopBar from './components/TopBar'; import TopBar from './components/TopBar';
import { usePersistentState } from './lib/usePersistentState'; import { usePersistentState } from './lib/usePersistentState';
// Only mounted when the user opens them, so they are separate chunks: the grid
// and the editor are what the first paint needs.
const AdminPanel = lazy(() => import('./components/AdminPanel'));
const CompareView = lazy(() => import('./components/CompareView'));
const ImmichPanel = lazy(() => import('./components/ImmichPanel'));
const MergeModal = lazy(() => import('./components/MergeModal'));
const PrintModal = lazy(() => import('./components/PrintModal'));
const ShareModal = lazy(() => import('./components/ShareModal'));
import { import {
currentUser, currentUser,
deleteEventRemote, deleteEventRemote,
@@ -68,7 +71,7 @@ import type { MergeResult } from './lib/merge';
import { evictBitmap } from './lib/images'; import { evictBitmap } from './lib/images';
import { importFiles, uid } from './lib/import'; import { importFiles, uid } from './lib/import';
import { PRESETS } from './lib/presets'; import { PRESETS } from './lib/presets';
import { downloadXmp, readXmpFile, xmpToEdits } from './lib/xmp'; import { downloadXmp, readXmpFile, xmpToEdits, xmpToMetadata } from './lib/xmp';
import type { import type {
Edits, Edits,
EventRecord, EventRecord,
@@ -2096,12 +2099,63 @@ export default function App() {
try { try {
const xml = await readXmpFile(); const xml = await readXmpFile();
if (!xml) return; if (!xml) return;
const result = xmpToEdits(xml, target.edits);
updatePhoto(target.id, { edits: result.edits }, 'Import XMP sidecar'); // A sidecar can carry a grade, cataloguing fields, or both. Read the two
// halves independently: a metadata-only file from a DAM must not fail for
// lacking crs: settings, and a grade must not be rejected for lacking
// keywords. Whichever half is present is applied; neither wipes the other.
let edits = target.edits;
let settingsNote = '';
try {
const result = xmpToEdits(xml, target.edits);
edits = result.edits;
settingsNote =
result.source === 'luminary'
? 'Luminary settings'
: `${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`;
} catch {
settingsNote = '';
}
const meta = xmpToMetadata(xml);
const patch: Partial<PhotoRecord> = {};
const fields: string[] = [];
if (edits !== target.edits) patch.edits = edits;
if (meta.rating !== undefined) {
patch.rating = meta.rating;
fields.push('rating');
}
if (meta.label) {
patch.color = meta.label;
fields.push('label');
}
const keywords = new Set(target.keywords);
for (const word of meta.keywords) keywords.add(word);
if (keywords.size !== target.keywords.length) {
patch.keywords = [...keywords];
fields.push('keywords');
}
const paths = new Set(target.keywordPaths ?? []);
for (const path of meta.keywordPaths) paths.add(path);
if (paths.size !== (target.keywordPaths?.length ?? 0)) {
patch.keywordPaths = [...paths];
fields.push('keyword paths');
}
if (Object.keys(meta.iptc).length > 0) {
patch.iptc = { ...target.iptc, ...meta.iptc };
fields.push('IPTC');
}
if (meta.title && !target.title) patch.title = meta.title;
if (meta.caption) patch.caption = meta.caption;
if (meta.creator) patch.creator = meta.creator;
if (meta.copyright) patch.copyright = meta.copyright;
if (!patch.edits && fields.length === 0) {
throw new Error('That sidecar has no settings or metadata to import');
}
updatePhoto(target.id, patch, 'Import XMP sidecar');
setToast( setToast(
result.source === 'luminary' [settingsNote, fields.join(', ')].filter(Boolean).join(' · ') || 'Imported the sidecar',
? 'Imported Luminary settings from the sidecar'
: `Imported ${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`,
); );
} catch (err) { } catch (err) {
setToast(err instanceof Error ? err.message : 'Could not import the sidecar'); setToast(err instanceof Error ? err.message : 'Could not import the sidecar');
@@ -2513,6 +2567,9 @@ export default function App() {
onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)} onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)}
metadataPresets={metadataPresets} metadataPresets={metadataPresets}
keywordLibrary={[...new Set(photos.flatMap((photo) => photo.keywords))].sort()} keywordLibrary={[...new Set(photos.flatMap((photo) => photo.keywords))].sort()}
keywordPathLibrary={[
...new Set(photos.flatMap((photo) => photo.keywordPaths ?? [])),
].sort()}
onSaveSnapshot={(name) => saveSnapshot(activePhoto.id, name)} onSaveSnapshot={(name) => saveSnapshot(activePhoto.id, name)}
onRestoreSnapshot={(snapshot) => restoreSnapshot(activePhoto.id, snapshot)} onRestoreSnapshot={(snapshot) => restoreSnapshot(activePhoto.id, snapshot)}
onDeleteSnapshot={(snapshot) => deleteSnapshot(activePhoto.id, snapshot.id)} onDeleteSnapshot={(snapshot) => deleteSnapshot(activePhoto.id, snapshot.id)}
@@ -2537,6 +2594,7 @@ export default function App() {
initialFiles={pendingFiles} initialFiles={pendingFiles}
existing={photos} existing={photos}
cloud={cloudUser ? { uploadOriginal, push: pushPhoto } : null} cloud={cloudUser ? { uploadOriginal, push: pushPhoto } : null}
local={localMode}
onNeedServer={() => { onNeedServer={() => {
setImportOpen(false); setImportOpen(false);
setCloudError(null); setCloudError(null);
@@ -2563,32 +2621,38 @@ export default function App() {
)} )}
{compareOpen && selected.length >= 2 && selected.length <= 4 && ( {compareOpen && selected.length >= 2 && selected.length <= 4 && (
<CompareView <Suspense fallback={null}>
photos={selected <CompareView
.map((id) => photos.find((photo) => photo.id === id)) photos={selected
.filter((photo): photo is PhotoRecord => Boolean(photo)) .map((id) => photos.find((photo) => photo.id === id))
.slice(0, 4)} .filter((photo): photo is PhotoRecord => Boolean(photo))
onClose={() => setCompareOpen(false)} .slice(0, 4)}
onOpen={(id) => { onClose={() => setCompareOpen(false)}
setCompareOpen(false); onOpen={(id) => {
openPhoto(id); setCompareOpen(false);
}} openPhoto(id);
/> }}
/>
</Suspense>
)} )}
{printOpen && ( {printOpen && (
<PrintModal <Suspense fallback={null}>
photos={photos.filter((photo) => selected.includes(photo.id))} <PrintModal
onClose={() => setPrintOpen(false)} photos={photos.filter((photo) => selected.includes(photo.id))}
/> onClose={() => setPrintOpen(false)}
/>
</Suspense>
)} )}
{mergeOpen && ( {mergeOpen && (
<MergeModal <Suspense fallback={null}>
photos={photos.filter((photo) => selected.includes(photo.id))} <MergeModal
onClose={() => setMergeOpen(false)} photos={photos.filter((photo) => selected.includes(photo.id))}
onDone={(result) => void addMergedPhoto(result)} onClose={() => setMergeOpen(false)}
/> onDone={(result) => void addMergedPhoto(result)}
/>
</Suspense>
)} )}
{exportOpen && ( {exportOpen && (
@@ -2638,13 +2702,15 @@ export default function App() {
const shared = events.find((e) => e.id === shareEventId); const shared = events.find((e) => e.id === shareEventId);
if (!shared) return null; if (!shared) return null;
return ( return (
<ShareModal <Suspense fallback={null}>
event={shared} <ShareModal
photos={livePhotos.filter((p) => p.eventId === shared.id)} event={shared}
onClose={() => setShareEventId(null)} photos={livePhotos.filter((p) => p.eventId === shared.id)}
onToast={setToast} onClose={() => setShareEventId(null)}
onProofPublished={handleProofPublished} onToast={setToast}
/> onProofPublished={handleProofPublished}
/>
</Suspense>
); );
})()} })()}
@@ -2681,26 +2747,30 @@ export default function App() {
)} )}
{adminOpen && cloudUser && !localMode && ( {adminOpen && cloudUser && !localMode && (
<AdminPanel <Suspense fallback={null}>
user={cloudUser} <AdminPanel
onClose={() => setAdminOpen(false)} user={cloudUser}
onChanged={() => { onClose={() => setAdminOpen(false)}
void getHealth().then((health) => setCloudHealth(health)); onChanged={() => {
void getImmichStatus().then(setImmichStatus).catch(() => undefined); void getHealth().then((health) => setCloudHealth(health));
}} void getImmichStatus().then(setImmichStatus).catch(() => undefined);
onRestored={() => void refreshCatalogFromServer()} }}
/> onRestored={() => void refreshCatalogFromServer()}
/>
</Suspense>
)} )}
{immichOpen && cloudUser && ( {immichOpen && cloudUser && (
<ImmichPanel <Suspense fallback={null}>
onClose={() => setImmichOpen(false)} <ImmichPanel
onChanged={() => { onClose={() => setImmichOpen(false)}
void getImmichStatus().then(setImmichStatus).catch(() => undefined); onChanged={() => {
void refreshCatalogFromServer(); void getImmichStatus().then(setImmichStatus).catch(() => undefined);
}} void refreshCatalogFromServer();
onToast={setToast} }}
/> onToast={setToast}
/>
</Suspense>
)} )}
{menu && {menu &&
+98 -26
View File
@@ -16,6 +16,7 @@ import type { Preview16 } from '../lib/preview16';
import { useMediaQuery } from '../lib/useMediaQuery'; import { useMediaQuery } from '../lib/useMediaQuery';
import { usePersistentState } from '../lib/usePersistentState'; import { usePersistentState } from '../lib/usePersistentState';
import { solveWhiteBalance } from '../lib/whiteBalance'; import { solveWhiteBalance } from '../lib/whiteBalance';
import { applyPresetEdits } from '../lib/presets';
import { buildAutoMask, type AutoMaskKind } from '../lib/autoMask'; import { buildAutoMask, type AutoMaskKind } from '../lib/autoMask';
import { import {
buildLensCorrection, buildLensCorrection,
@@ -157,6 +158,8 @@ interface Props {
onVirtualCopy: () => void; onVirtualCopy: () => void;
metadataPresets: MetadataPreset[]; metadataPresets: MetadataPreset[];
keywordLibrary: string[]; keywordLibrary: string[];
/** Hierarchical paths already in the library, for metadata suggestions. */
keywordPathLibrary?: string[];
onSaveSnapshot: (name: string) => void; onSaveSnapshot: (name: string) => void;
onRestoreSnapshot: (snapshot: Snapshot) => void; onRestoreSnapshot: (snapshot: Snapshot) => void;
onDeleteSnapshot: (snapshot: Snapshot) => void; onDeleteSnapshot: (snapshot: Snapshot) => void;
@@ -191,6 +194,7 @@ export default function Develop({
onVirtualCopy, onVirtualCopy,
metadataPresets, metadataPresets,
keywordLibrary, keywordLibrary,
keywordPathLibrary = [],
onSaveSnapshot, onSaveSnapshot,
onRestoreSnapshot, onRestoreSnapshot,
onDeleteSnapshot, onDeleteSnapshot,
@@ -276,6 +280,9 @@ export default function Develop({
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null); const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
const [lensSplit, setLensSplit] = useState(false); const [lensSplit, setLensSplit] = useState(false);
const [lensSplitAt, setLensSplitAt] = useState(0.5); const [lensSplitAt, setLensSplitAt] = useState(0.5);
// The whole edit compared with the untouched source, split by a drag line.
const [splitView, setSplitView] = useState(false);
const [splitAt, setSplitAt] = useState(0.5);
const [lensState, setLensState] = useState<{ loading: boolean; error: string | null }>({ const [lensState, setLensState] = useState<{ loading: boolean; error: string | null }>({
loading: false, loading: false,
error: null, error: null,
@@ -373,11 +380,16 @@ export default function Develop({
onSelect(p.id); onSelect(p.id);
}; };
const moveLensSplit = (e: React.PointerEvent<HTMLButtonElement>) => { // Both splits drag the same way: the handle sits on the line, and its
const rect = e.currentTarget.parentElement?.getBoundingClientRect(); // percentage follows the pointer across the canvas.
if (!rect || rect.width <= 0) return; const dragSplit =
setLensSplitAt(clampNum((e.clientX - rect.left) / rect.width, 0.02, 0.98)); (set: (at: number) => void) => (e: React.PointerEvent<HTMLButtonElement>) => {
}; const rect = e.currentTarget.parentElement?.getBoundingClientRect();
if (!rect || rect.width <= 0) return;
set(clampNum((e.clientX - rect.left) / rect.width, 0.02, 0.98));
};
const moveLensSplit = dragSplit(setLensSplitAt);
const moveSplit = dragSplit(setSplitAt);
const setEdits = useCallback( const setEdits = useCallback(
(patch: Partial<Edits>, label: string) => { (patch: Partial<Edits>, label: string) => {
@@ -546,7 +558,11 @@ export default function Develop({
if (!renderer || !canvas || !bitmap) return; if (!renderer || !canvas || !bitmap) return;
if (stage.w < 40 || stage.h < 40) return; if (stage.w < 40 || stage.h < 40) return;
const activeEdits = showOriginal ? { ...defaultEdits(), crop: edits.crop } : edits; // Holding \ shows the untouched source full-frame; the split paints the same
// render over the left of its drag line, and steps aside while \ is held.
const beforeEdits = { ...defaultEdits(), crop: edits.crop };
const splitOn = splitView && !showOriginal;
const activeEdits = showOriginal ? beforeEdits : edits;
const frame = rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter); const frame = rotatedBounds(bitmap.width, bitmap.height, edits.crop.angle, edits.crop.quarter);
const content: Rect = cropMode const content: Rect = cropMode
? { x: 0, y: 0, w: 1, h: 1 } ? { x: 0, y: 0, w: 1, h: 1 }
@@ -616,7 +632,7 @@ export default function Develop({
renderer.setImage(bitmap, hdrSource); renderer.setImage(bitmap, hdrSource);
// "Show original" must show the untouched source, not the cleaned proxy. // "Show original" must show the untouched source, not the cleaned proxy.
renderer.setDenoised(showOriginal ? null : denoisedBitmap, activeEdits.aiDenoise.amount / 100); renderer.setDenoised(showOriginal ? null : denoisedBitmap, activeEdits.aiDenoise.amount / 100);
renderer.render(activeEdits, { const frameOpts = {
width: pxW, width: pxW,
height: pxH, height: pxH,
cropPreview: cropMode, cropPreview: cropMode,
@@ -631,11 +647,30 @@ export default function Develop({
upscale: dpr * cap * fitScale * zoomFactor > 1.1, upscale: dpr * cap * fitScale * zoomFactor > 1.1,
clipPreview, clipPreview,
clipping: clipping ?? undefined, clipping: clipping ?? undefined,
};
renderer.render(activeEdits, {
...frameOpts,
lens: showOriginal ? null : lensCorrection, lens: showOriginal ? null : lensCorrection,
lensSplit: lensSplit && !showOriginal ? lensSplitAt : undefined, lensSplit: lensSplit && !splitOn ? lensSplitAt : undefined,
maskView, maskView,
maskStrength: maskStrength / 100, maskStrength: maskStrength / 100,
}); });
if (splitOn) {
// Paint the untouched source over the left half. The scissor is in
// device pixels and the same view is reused, so the halves line up.
renderer.setDenoised(null, 0);
renderer.render(beforeEdits, {
...frameOpts,
histogram: false,
lens: null,
maskView: -1,
clipPreview: false,
scissor: { x: 0, w: Math.round(pxW * splitAt) },
});
// Restore what the rest of the frame and the eyedropper read from.
renderer.setDenoised(denoisedBitmap, edits.aiDenoise.amount / 100);
renderer.setLensCorrection(lensCorrection);
}
histRef.current = renderer.histogram; histRef.current = renderer.histogram;
setHistVersion((v) => v + 1); setHistVersion((v) => v + 1);
} catch (err) { } catch (err) {
@@ -656,6 +691,8 @@ export default function Develop({
lensCorrection, lensCorrection,
lensSplit, lensSplit,
lensSplitAt, lensSplitAt,
splitView,
splitAt,
localMode, localMode,
localSelected, localSelected,
maskOverlay, maskOverlay,
@@ -1611,18 +1648,9 @@ export default function Develop({
const applyPreset = useCallback( const applyPreset = useCallback(
(preset: Preset) => { (preset: Preset) => {
const next: Edits = // The look grades over the photo's current white balance, so a correction
preset.id === 'original' // made first is the base it is applied against.
? { ...defaultEdits(), crop: photo.edits.crop } const next = applyPresetEdits(photo.edits, preset);
: {
...photo.edits,
...preset.edits,
crop: photo.edits.crop,
// The camera profile belongs to the body that produced the raw.
cameraProfile: photo.edits.cameraProfile,
// A strong film response must not leak into the next look.
redscale: preset.edits.redscale ?? 0,
};
onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`); onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`);
}, },
[onUpdate, photo.id, photo.edits], [onUpdate, photo.id, photo.edits],
@@ -1740,6 +1768,7 @@ export default function Develop({
onUpdate={(patch) => onUpdate(photo.id, patch)} onUpdate={(patch) => onUpdate(photo.id, patch)}
presets={metadataPresets} presets={metadataPresets}
keywordLibrary={keywordLibrary} keywordLibrary={keywordLibrary}
keywordPathLibrary={keywordPathLibrary}
onSavePreset={onSaveMetadataPreset} onSavePreset={onSaveMetadataPreset}
onDeletePreset={onDeleteMetadataPreset} onDeletePreset={onDeleteMetadataPreset}
/> />
@@ -1801,6 +1830,7 @@ export default function Develop({
'separator', 'separator',
{ label: 'Crop & Straighten', shortcut: 'C', onSelect: () => setCropMode((v) => !v) }, { label: 'Crop & Straighten', shortcut: 'C', onSelect: () => setCropMode((v) => !v) },
{ label: 'Before / After', shortcut: '\\', onSelect: () => setShowOriginal((v) => !v) }, { label: 'Before / After', shortcut: '\\', onSelect: () => setShowOriginal((v) => !v) },
{ label: 'Before / After split', onSelect: () => setSplitView((v) => !v) },
'separator', 'separator',
{ label: 'Copy settings', shortcut: '⌘C', onSelect: onCopy }, { label: 'Copy settings', shortcut: '⌘C', onSelect: onCopy },
{ label: 'Paste settings', shortcut: '⌘V', onSelect: () => onPaste([photo.id]), disabled: !clipboard }, { label: 'Paste settings', shortcut: '⌘V', onSelect: () => onPaste([photo.id]), disabled: !clipboard },
@@ -1884,6 +1914,14 @@ export default function Develop({
> >
Before / After Before / After
</button> </button>
<button
className={`btn ghost small ${splitView ? 'on' : ''}`}
onClick={() => setSplitView((v) => !v)}
aria-pressed={splitView}
title="Compare the edit with the original on either side of a draggable line"
>
Split
</button>
<button <button
className={`btn ghost small ${autoSync ? 'on' : ''}`} className={`btn ghost small ${autoSync ? 'on' : ''}`}
onClick={() => setAutoSync((v) => !v)} onClick={() => setAutoSync((v) => !v)}
@@ -2097,14 +2135,14 @@ export default function Develop({
toggleZoom(e.clientX, e.clientY); toggleZoom(e.clientX, e.clientY);
}} }}
/> />
{lensSplit && lensCorrection && !showOriginal && ( {lensSplit && lensCorrection && !showOriginal && !splitView && (
<div className="lens-split"> <div className="compare-split">
<div className="lens-split-line" style={{ left: `${lensSplitAt * 100}%` }} /> <div className="compare-split-line" style={{ left: `${lensSplitAt * 100}%` }} />
<span className="lens-split-label before">Before</span> <span className="compare-split-label before">Before</span>
<span className="lens-split-label after">After</span> <span className="compare-split-label after">After</span>
<button <button
type="button" type="button"
className="lens-split-handle" className="compare-split-handle"
style={{ left: `${lensSplitAt * 100}%` }} style={{ left: `${lensSplitAt * 100}%` }}
aria-label="Drag to move the lens correction split" aria-label="Drag to move the lens correction split"
title="Drag to compare lens correction" title="Drag to compare lens correction"
@@ -2131,6 +2169,40 @@ export default function Develop({
</button> </button>
</div> </div>
)} )}
{splitView && !showOriginal && (
<div className="compare-split">
<div className="compare-split-line" style={{ left: `${splitAt * 100}%` }} />
<span className="compare-split-label before">Before</span>
<span className="compare-split-label after">After</span>
<button
type="button"
className="compare-split-handle"
style={{ left: `${splitAt * 100}%` }}
aria-label="Drag to move the before / after split"
title="Drag to compare the edit with the original"
onPointerDown={(e) => {
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
moveSplit(e);
}}
onPointerMove={(e) => {
if (e.currentTarget.hasPointerCapture(e.pointerId)) moveSplit(e);
}}
onPointerUp={(e) => {
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(e.pointerId);
}
}}
onPointerCancel={(e) => {
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(e.pointerId);
}
}}
>
↔
</button>
</div>
)}
{healMode && bitmap && (() => { {healMode && bitmap && (() => {
const geo = geoRef.current; const geo = geoRef.current;
const view = geo.view; const view = geo.view;
+105
View File
@@ -0,0 +1,105 @@
import { Component, type ErrorInfo, type ReactNode } from 'react';
interface Props {
children: ReactNode;
}
interface State {
error: Error | null;
componentStack: string;
version: string;
copied: boolean;
}
/**
* Without this, one exception anywhere in the tree unmounts React and leaves a
* blank page with nothing to report. The boundary keeps a way back (reload)
* and a way to tell support what happened, and says plainly that the library
* itself is untouched.
*/
export default class ErrorBoundary extends Component<Props, State> {
state: State = { error: null, componentStack: '', version: '', copied: false };
static getDerivedStateFromError(error: Error): Partial<State> {
return { error };
}
componentDidCatch(error: Error, info: ErrorInfo) {
console.error('Luminary crashed while rendering', error, info.componentStack);
this.setState({ componentStack: info.componentStack ?? '' });
// The version is a nicety for the diagnostics; the page works without it.
fetch('/api/health', { credentials: 'same-origin' })
.then((res) => (res.ok ? res.json() : null))
.then((body: { version?: string } | null) => {
if (body?.version) this.setState({ version: body.version });
})
.catch(() => undefined);
}
private diagnostics(): string {
const error = this.state.error;
return [
'Luminary crash report',
`Version: ${this.state.version || 'unknown'}`,
`When: ${new Date().toISOString()}`,
`Page: ${window.location.pathname}${window.location.search}`,
`Browser: ${navigator.userAgent}`,
`Screen: ${window.screen.width}x${window.screen.height} @${window.devicePixelRatio}x`,
'',
`Error: ${error?.name ?? 'Error'}: ${error?.message ?? 'unknown'}`,
error?.stack ?? '',
'',
'Component stack:',
this.state.componentStack,
].join('\n');
}
private async copyDiagnostics() {
try {
await navigator.clipboard.writeText(this.diagnostics());
this.setState({ copied: true });
window.setTimeout(() => this.setState({ copied: false }), 2500);
} catch {
// Clipboard access can be denied; the email link still carries the report.
this.setState({ copied: false });
}
}
render() {
const error = this.state.error;
if (!error) return this.props.children;
const subject = encodeURIComponent('Luminary crash report');
const body = encodeURIComponent(this.diagnostics().slice(0, 1800));
const mailto = `mailto:bhursey@gmail.com?subject=${subject}&body=${body}`;
return (
<section className="crash-screen" role="alert">
<div className="crash-card">
<h1>Luminary hit an unexpected error</h1>
<p>
Your photos, edits and catalog are safe on disk — nothing was deleted. Reloading
usually clears it. If it keeps happening, send the diagnostics below so it can be
fixed.
</p>
<p className="crash-message">{error.message || 'Unknown error'}</p>
<div className="btn-row">
<button className="btn primary" onClick={() => window.location.reload()}>
Reload Luminary
</button>
<button className="btn ghost" onClick={() => void this.copyDiagnostics()}>
{this.state.copied ? 'Copied' : 'Copy diagnostics'}
</button>
<a className="btn ghost" href={mailto}>
Email support
</a>
</div>
<details className="crash-details">
<summary>Technical details</summary>
<pre>{this.diagnostics()}</pre>
</details>
</div>
</section>
);
}
}
+22 -3
View File
@@ -23,6 +23,7 @@ const FORMATS: { value: ExportFormat; label: string }[] = [
{ value: 'png', label: 'PNG (8-bit)' }, { value: 'png', label: 'PNG (8-bit)' },
{ value: 'webp', label: 'WebP' }, { value: 'webp', label: 'WebP' },
{ value: 'tiff16', label: 'TIFF (16-bit)' }, { value: 'tiff16', label: 'TIFF (16-bit)' },
{ value: 'jxl', label: 'JPEG XL' },
]; ];
/** /**
@@ -360,7 +361,7 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
)} )}
</div> </div>
{(opts.format === 'jpeg' || opts.format === 'webp') && ( {(opts.format === 'jpeg' || opts.format === 'webp' || opts.format === 'jxl') && (
<label className="field"> <label className="field">
<span>Quality · {opts.quality}</span> <span>Quality · {opts.quality}</span>
<input <input
@@ -369,11 +370,29 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
max={100} max={100}
value={opts.quality} value={opts.quality}
onChange={(e) => patch({ quality: Number(e.target.value) })} onChange={(e) => patch({ quality: Number(e.target.value) })}
disabled={busy} disabled={busy || (opts.format === 'jxl' && opts.jxlLossless === true)}
/> />
</label> </label>
)} )}
{opts.format === 'jxl' && (
<>
<label className="check-row">
<input
type="checkbox"
checked={opts.jxlLossless === true}
onChange={(e) => patch({ jxlLossless: e.target.checked })}
disabled={busy}
/>
Lossless — keeps every pixel and ignores the quality setting
</label>
<p className="muted small">
JPEG XL exports are 8-bit sRGB. Chrome, Firefox and Safari open them; Microsoft Edge
does not yet.
</p>
</>
)}
{sample && <ExportDetailStrip photo={sample} size={previewSize} />} {sample && <ExportDetailStrip photo={sample} size={previewSize} />}
<label className="field"> <label className="field">
@@ -478,7 +497,7 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
type="checkbox" type="checkbox"
checked={opts.embedProfile} checked={opts.embedProfile}
onChange={(e) => patch({ embedProfile: e.target.checked })} onChange={(e) => patch({ embedProfile: e.target.checked })}
disabled={opts.format === 'webp' || opts.format === 'png'} disabled={opts.format === 'webp' || opts.format === 'png' || opts.format === 'jxl'}
/> />
Embed {COLOR_SPACE_OPTIONS.find((option) => option.value === (opts.colorSpace ?? 'srgb'))?.label ?? 'sRGB'} profile (JPEG/TIFF) Embed {COLOR_SPACE_OPTIONS.find((option) => option.value === (opts.colorSpace ?? 'srgb'))?.label ?? 'sRGB'} profile (JPEG/TIFF)
</label> </label>
+57 -10
View File
@@ -18,6 +18,8 @@ interface Props {
immichEnabled?: boolean; immichEnabled?: boolean;
onCreateImmichGallery?: (eventId: string) => Promise<EventRecord>; onCreateImmichGallery?: (eventId: string) => Promise<EventRecord>;
cloud?: CloudImport | null; cloud?: CloudImport | null;
/** Desktop bundle: the decoder runs on this PC rather than a team server. */
local?: boolean;
onNeedServer: () => void; onNeedServer: () => void;
} }
@@ -32,6 +34,7 @@ export default function ImportModal({
immichEnabled = false, immichEnabled = false,
onCreateImmichGallery, onCreateImmichGallery,
cloud, cloud,
local = false,
onNeedServer, onNeedServer,
}: Props) { }: Props) {
const startId = initialEventId !== 'all' && initialEventId !== 'unsorted' ? initialEventId : events[0]?.id ?? '__new'; const startId = initialEventId !== 'all' && initialEventId !== 'unsorted' ? initialEventId : events[0]?.id ?? '__new';
@@ -43,6 +46,9 @@ export default function ImportModal({
const [progress, setProgress] = useState<ImportProgress | null>(null); const [progress, setProgress] = useState<ImportProgress | null>(null);
const [failures, setFailures] = useState<string[]>([]); const [failures, setFailures] = useState<string[]>([]);
const [allowDuplicates, setAllowDuplicates] = useState(false); const [allowDuplicates, setAllowDuplicates] = useState(false);
// 16-bit is the default an editor would expect, and it is what a raw import
// should keep unless the whole point is a smaller library.
const [sidecar16, setSidecar16] = useState(true);
const [createGallery, setCreateGallery] = useState(immichEnabled); const [createGallery, setCreateGallery] = useState(immichEnabled);
const [galleryCreated, setGalleryCreated] = useState(false); const [galleryCreated, setGalleryCreated] = useState(false);
const [galleryError, setGalleryError] = useState<string | null>(null); const [galleryError, setGalleryError] = useState<string | null>(null);
@@ -125,7 +131,15 @@ export default function ImportModal({
); );
} }
} }
const result = await importFiles(readyFiles, targetId, [], setProgress, cloud ?? null, controller.signal); const result = await importFiles(
readyFiles,
targetId,
[],
setProgress,
cloud ?? null,
controller.signal,
{ sidecar16 },
);
if (result.photos.length) onImported(result.photos, targetId); if (result.photos.length) onImported(result.photos, targetId);
let published = 0; let published = 0;
@@ -278,7 +292,8 @@ export default function ImportModal({
<strong>Drop photos here</strong> <strong>Drop photos here</strong>
<p className="muted"> <p className="muted">
or click to choose files. JPEG, PNG, WebP, AVIF, TIFF and camera raw (CR2, CR3, NEF, or click to choose files. JPEG, PNG, WebP, AVIF, TIFF and camera raw (CR2, CR3, NEF,
ARW, ORF, RW2, RAF, DNG, PEF…) — raw needs the team server. ARW, ORF, RW2, RAF, DNG, PEF…) — raw needs{' '}
{local ? 'the local engine' : 'the team server'}.
</p> </p>
</div> </div>
<input <input
@@ -329,21 +344,51 @@ export default function ImportModal({
<strong> <strong>
{rawCount} raw file{rawCount === 1 ? '' : 's'} cannot be read by the browser. {rawCount} raw file{rawCount === 1 ? '' : 's'} cannot be read by the browser.
</strong>{' '} </strong>{' '}
They are decoded by the team server, so sign in before importing — or import them later {local
from the library. ? 'They are decoded by the local engine on this PC. Check that Luminary is running, then import again.'
<button className="btn primary small banner-action" onClick={onNeedServer} disabled={busy}> : 'They are decoded by the team server, so sign in before importing — or import them later from the library.'}
Sign in to the server {!local && (
</button> <button className="btn primary small banner-action" onClick={onNeedServer} disabled={busy}>
Sign in to the server
</button>
)}
</div> </div>
)} )}
{rawCount > 0 && cloud && ( {rawCount > 0 && cloud && (
<div className="banner info"> <div className="banner info">
Raw files are demosaiced by the server (LibRaw), a few at a time in parallel. Each file {local
usually takes 2–4 seconds. ? 'Raw files are demosaiced by the Luminary local engine (LibRaw) on this PC, two ' +
'at a time; the rest of your selection waits its turn. A 24 MP raw takes a few ' +
'seconds; a 40 MP compressed Fuji file takes closer to twenty. Nothing leaves ' +
'your computer.'
: 'Raw files are demosaiced by the server (LibRaw), two at a time; the rest of your ' +
'selection waits its turn. A 24 MP raw takes a few seconds; a 40 MP compressed ' +
'Fuji file takes closer to twenty.'}
{' '}A file the engine cannot decode still imports from the camera’s own preview.
</div> </div>
)} )}
{rawCount > 0 && cloud && (
<>
<label className="check-row">
<input
type="checkbox"
checked={sidecar16}
onChange={(e) => setSidecar16(e.target.checked)}
disabled={busy}
/>
Import raws at 16-bit (recommended)
</label>
<p className="muted small">
A 16-bit sidecar keeps every level the decoder read, so recovering shadows and
highlights works from 65,536 steps per channel instead of 256. It costs roughly
25× the JPEG in disk and download. Uncheck to import at 8-bit instead: smaller,
quicker to upload, but graded from the JPEG.
</p>
</>
)}
{progress && ( {progress && (
<div className="progress"> <div className="progress">
<div className="progress-bar"> <div className="progress-bar">
@@ -353,7 +398,9 @@ export default function ImportModal({
/> />
</div> </div>
<div className="muted small"> <div className="muted small">
{progress.done} / {progress.total} {progress.current ? `· ${progress.current}` : ''} {progress.done} / {progress.total}
{progress.waiting ? ` · ${progress.waiting} waiting` : ''}
{progress.current ? ` · ${progress.current}` : ''}
</div> </div>
</div> </div>
)} )}
+1 -1
View File
@@ -101,7 +101,7 @@ LUMINARY
{loadError && ( {loadError && (
<> <>
<span className="join-eyebrow">Invite</span> <span className="join-eyebrow">Invite</span>
<h1>Can’t reach the server</h1> <h1>Can’t reach Luminary</h1>
<p className="muted">{loadError}</p> <p className="muted">{loadError}</p>
<a className="btn ghost wide" href="/"> <a className="btn ghost wide" href="/">
Go to Luminary Go to Luminary
+203 -14
View File
@@ -3,7 +3,16 @@ import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_COMPONENTS, MA
import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto'; import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto';
import { autoNoiseFor } from '../lib/noiseProfile'; import { autoNoiseFor } from '../lib/noiseProfile';
import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api'; import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api';
import {
DENOISE_MODELS,
denoiseProgressLabel,
withDenoiseRender,
type DenoiseModel,
} from '../lib/denoiseModels';
import type { DenoiseProgress } from '../lib/api';
import { clamp } from '../lib/curves'; import { clamp } from '../lib/curves';
import { estimateKelvin, expressWhiteBalance, wbGainWithLook } from '../lib/whiteBalance';
import { addKeywordPath, removeKeywordPath } from '../lib/keywords';
import type { import type {
CurveChannel, CurveChannel,
Edits, Edits,
@@ -100,6 +109,12 @@ export function BasicPanel({
// come back with neutral values, so Auto WB matched As shot exactly. // come back with neutral values, so Auto WB matched As shot exactly.
const thumbSrc = photo.thumbUrl ?? photo.thumb; const thumbSrc = photo.thumbUrl ?? photo.thumb;
// A look adds its cast to the correction already in the sliders; this shows what
// that leaves the white balance at, so the final balance stays visible.
const lookCast = edits.presetLook && (edits.presetLook.temp || edits.presetLook.tint) ? edits.presetLook : null;
const finalWb = lookCast ? expressWhiteBalance(wbGainWithLook(edits.temp, edits.tint, edits.kelvin, lookCast)) : null;
const signed = (v: number) => (v > 0 ? `+${v}` : String(v));
const auto = async () => { const auto = async () => {
setAutoBusy(true); setAutoBusy(true);
try { try {
@@ -173,6 +188,23 @@ export function BasicPanel({
onChange={(v) => set({ tint: v }, 'Tint')} onChange={(v) => set({ tint: v }, 'Tint')}
track="linear-gradient(90deg,#54b364,#a8b6c6,#c56ad2)" track="linear-gradient(90deg,#54b364,#a8b6c6,#c56ad2)"
/> />
{lookCast && finalWb && (
<div
className="wb-look"
title="The look grades over your white balance, so it adds its own temperature and tint on top. These are the numbers the photo is actually graded at."
>
<span>
Look cast <b>{signed(lookCast.temp)} / {signed(lookCast.tint)}</b>
</span>
<span className="wb-look-final">
Final{' '}
{edits.kelvin != null
? `≈ ${Math.round(estimateKelvin(wbGainWithLook(edits.temp, edits.tint, edits.kelvin, lookCast)) / 10) * 10} K`
: `temp ${signed(finalWb.temp)}`}{' '}
· tint {signed(finalWb.tint)}
</span>
</div>
)}
<div className="subhead"> <div className="subhead">
<span>Tone</span> <span>Tone</span>
@@ -610,34 +642,60 @@ export function EffectsPanel({ edits, photo, set, grainFreeze }: PanelSetProps &
export function DetailPanel({ edits, photo, set }: PanelSetProps) { export function DetailPanel({ edits, photo, set }: PanelSetProps) {
const [aiBusy, setAiBusy] = useState(false); const [aiBusy, setAiBusy] = useState(false);
const [aiNote, setAiNote] = useState<string | null>(null); const [aiNote, setAiNote] = useState<string | null>(null);
const [aiStartedAt, setAiStartedAt] = useState<number | null>(null);
const [aiElapsed, setAiElapsed] = useState(0);
const [aiProgress, setAiProgress] = useState<DenoiseProgress | null>(null);
const aiActive = Boolean(edits.aiDenoise.key); const aiActive = Boolean(edits.aiDenoise.key);
// A render reports no progress of its own, so the elapsed time is the one
// honest measurement the panel can show. It ticks only while one is running:
// a full-size frame is seconds of solid CPU on the server, not a spinner.
useEffect(() => {
if (aiStartedAt == null) return;
setAiElapsed(0);
const timer = window.setInterval(
() => setAiElapsed(Math.round((performance.now() - aiStartedAt) / 1000)),
1000,
);
return () => window.clearInterval(timer);
}, [aiStartedAt]);
// Poll rather than stream: the job is seconds long, and a failed poll just // Poll rather than stream: the job is seconds long, and a failed poll just
// leaves the previous note on screen instead of breaking the panel. // leaves the previous note on screen instead of breaking the panel.
const generateAi = async () => { const generateAi = async (base: DenoiseModel = edits.aiDenoise.model) => {
if (aiBusy) return; if (aiBusy) return;
setAiBusy(true); setAiBusy(true);
setAiNote('Rendering the denoised version on the server…'); setAiStartedAt(performance.now());
setAiProgress(null);
setAiNote(null);
try { try {
const { jobId } = await startDenoise(photo.id); const { jobId } = await startDenoise(photo.id, base);
for (let attempt = 0; attempt < 180; attempt++) { for (let attempt = 0; attempt < 180; attempt++) {
await new Promise((resolve) => setTimeout(resolve, 1000)); await new Promise((resolve) => setTimeout(resolve, 1000));
const job = await getDenoiseJob(jobId); const job = await getDenoiseJob(jobId);
// The worker names its stage and counts SCUNet tiles; poll it rather than
// inventing a percentage on the client.
if (job.state === 'running') setAiProgress(job.progress ?? null);
if (job.state === 'done') { if (job.state === 'done') {
set({ aiDenoise: { ...edits.aiDenoise, key: job.key } }, 'AI denoise'); // `edits` here is the render captured when the run started -- before
// the chip click that picked the model was committed. Spreading it
// writes the previous model back, so an SCUNet render would flip the
// picker to Guided on completion. The key belongs to one specific
// base, so pin the model to the base that actually rendered.
set({ aiDenoise: withDenoiseRender(edits.aiDenoise, base, job.key) }, 'AI denoise');
// The pipeline tapers itself down on frames it measures as clean. That // The pipeline tapers itself down on frames it measures as clean. That
// taper is in the rendered file now, so report it -- the Amount slider // taper is in the rendered file now, so report it -- the Amount slider
// multiplies it rather than replacing it. // multiplies it rather than replacing it.
const applied = job.stats?.autoGate ?? 1; const applied = job.stats?.autoGate ?? 1;
const base = job.cached const note = job.cached
? 'Using the cached version' ? 'Using the cached version'
: job.ms != null : job.ms != null
? `Cleaned in ${(job.ms / 1000).toFixed(1)}s` ? `Cleaned in ${(job.ms / 1000).toFixed(1)}s`
: 'Denoise ready'; : 'Denoise ready';
setAiNote( setAiNote(
applied < 0.95 applied < 0.95
? `${base} · clean frame, correction reduced to ${Math.round(applied * 100)}%` ? `${note} · clean frame, correction reduced to ${Math.round(applied * 100)}%`
: base, : note,
); );
return; return;
} }
@@ -650,6 +708,8 @@ export function DetailPanel({ edits, photo, set }: PanelSetProps) {
} catch (err) { } catch (err) {
setAiNote(err instanceof Error ? err.message : 'Denoise failed'); setAiNote(err instanceof Error ? err.message : 'Denoise failed');
} finally { } finally {
setAiStartedAt(null);
setAiProgress(null);
setAiBusy(false); setAiBusy(false);
} }
}; };
@@ -747,12 +807,31 @@ export function DetailPanel({ edits, photo, set }: PanelSetProps) {
<button <button
className="chip tiny" className="chip tiny"
disabled={aiBusy} disabled={aiBusy}
onClick={generateAi} onClick={() => void generateAi()}
title="Clean up noise while keeping edges and fine texture" title="Clean up noise with a detail-preserving model"
> >
{aiBusy ? 'Working…' : aiActive ? 'Regenerate' : 'Generate'} {aiBusy ? 'Working…' : aiActive ? 'Regenerate' : 'Generate'}
</button> </button>
</div> </div>
<div className="model-picker" role="radiogroup" aria-label="AI denoise model">
{/* One render belongs to one model: switching mid-run would leave a chip
selected with no render behind it. */}
{DENOISE_MODELS.map((opt) => (
<button
key={opt.value}
type="button"
disabled={aiBusy}
className={`chip small ${edits.aiDenoise.model === opt.value ? 'on' : ''}`}
onClick={() => {
set({ aiDenoise: { ...edits.aiDenoise, model: opt.value } }, 'AI denoise model');
void generateAi(opt.value);
}}
title={opt.title}
>
{opt.label}
</button>
))}
</div>
{aiActive ? ( {aiActive ? (
<Slider <Slider
label="Amount" label="Amount"
@@ -763,10 +842,17 @@ export function DetailPanel({ edits, photo, set }: PanelSetProps) {
/> />
) : null} ) : null}
<p className="muted small panel-hint"> <p className="muted small panel-hint">
{aiNote ?? {aiBusy ? (
<>
{denoiseProgressLabel(aiProgress, edits.aiDenoise.model, aiElapsed)}. A full-size frame
can take a minute or two; the picker unlocks when it lands.
</>
) : (
aiNote ??
(aiActive (aiActive
? 'Detail-preserving denoise, rendered from the full proxy.' ? 'Detail-preserving denoise, rendered from the full proxy.'
: 'Removes noise only where there is no structure to keep.')} : 'Removes noise only where there is no structure to keep.')
)}
</p> </p>
{aiActive ? ( {aiActive ? (
<button <button
@@ -2601,6 +2687,7 @@ export function MetadataPanel({
onUpdate, onUpdate,
presets = [], presets = [],
keywordLibrary = [], keywordLibrary = [],
keywordPathLibrary = [],
onSavePreset, onSavePreset,
onDeletePreset, onDeletePreset,
}: { }: {
@@ -2609,6 +2696,8 @@ export function MetadataPanel({
onUpdate?: (patch: Partial<PhotoRecord>) => void; onUpdate?: (patch: Partial<PhotoRecord>) => void;
presets?: MetadataPreset[]; presets?: MetadataPreset[];
keywordLibrary?: string[]; keywordLibrary?: string[];
/** Existing hierarchical paths in the library, offered as suggestions. */
keywordPathLibrary?: string[];
onSavePreset?: (preset: Omit<MetadataPreset, 'id'>) => void; onSavePreset?: (preset: Omit<MetadataPreset, 'id'>) => void;
onDeletePreset?: (id: string) => void; onDeletePreset?: (id: string) => void;
}) { }) {
@@ -2644,11 +2733,21 @@ export function MetadataPanel({
const patch = (next: Partial<PhotoRecord>) => onUpdate?.(next); const patch = (next: Partial<PhotoRecord>) => onUpdate?.(next);
/**
* One entry point for both kinds of tag: a plain word stays flat, and
* `Nature > Birds` records the path and its ancestors. The leaf is added to
* `keywords` either way, so search and filters keep working on flat terms.
*/
const addKeyword = (raw?: string) => { const addKeyword = (raw?: string) => {
const value = (raw ?? keyword).trim().replace(/,$/, ''); const value = (raw ?? keyword).trim().replace(/,$/, '');
if (!value) return; if (!value) return;
const exists = photo.keywords.some((word) => word.toLowerCase() === value.toLowerCase()); patch(
if (!exists) patch({ keywords: [...photo.keywords, value.slice(0, 48)] }); addKeywordPath(
{ keywords: photo.keywords, keywordPaths: photo.keywordPaths ?? [] },
value,
/[>/|]/.test(value),
),
);
setKeyword(''); setKeyword('');
}; };
@@ -2656,6 +2755,19 @@ export function MetadataPanel({
patch({ keywords: photo.keywords.filter((item) => item !== word) }); patch({ keywords: photo.keywords.filter((item) => item !== word) });
}; };
const removePath = (path: string) => {
patch(
removeKeywordPath(
{ keywords: photo.keywords, keywordPaths: photo.keywordPaths ?? [] },
path,
),
);
};
const patchIptc = (field: keyof NonNullable<PhotoRecord['iptc']>, value: string) => {
patch({ iptc: { ...photo.iptc, [field]: value } });
};
const applyPreset = (id: string) => { const applyPreset = (id: string) => {
setPresetId(id); setPresetId(id);
const preset = presets.find((item) => item.id === id); const preset = presets.find((item) => item.id === id);
@@ -2734,11 +2846,32 @@ export function MetadataPanel({
</button> </button>
))} ))}
</div> </div>
{photo.keywordPaths?.length ? (
<>
<div className="metadata-keywords-head">
<span>Keyword paths</span>
<span className="muted small">{photo.keywordPaths.length}</span>
</div>
<div className="keyword-chips">
{photo.keywordPaths.map((path) => (
<button
key={path}
className="keyword-chip"
onClick={() => removePath(path)}
title="Remove this path and everything under it"
>
{path} <span aria-hidden="true">×</span>
</button>
))}
</div>
</>
) : null}
<div className="keyword-add"> <div className="keyword-add">
<input <input
value={keyword} value={keyword}
list="lumen-keyword-library" list="lumen-keyword-library"
placeholder="Add keyword…" placeholder="Add keyword, or Nature > Birds…"
onChange={(e) => setKeyword(e.target.value)} onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ',') { if (e.key === 'Enter' || e.key === ',') {
@@ -2755,9 +2888,65 @@ export function MetadataPanel({
{keywordLibrary.map((word) => ( {keywordLibrary.map((word) => (
<option key={word} value={word} /> <option key={word} value={word} />
))} ))}
{keywordPathLibrary.map((path) => (
<option key={`path:${path}`} value={path} />
))}
</datalist> </datalist>
</div> </div>
<div className="metadata-keywords-head">
<span>IPTC</span>
</div>
<label className="field">
<span>Headline</span>
<input
value={photo.iptc?.headline ?? ''}
placeholder="Who, what, where"
onChange={(e) => patchIptc('headline', e.target.value)}
disabled={!onUpdate}
/>
</label>
<div className="field-row">
<label className="field">
<span>Credit</span>
<input
value={photo.iptc?.credit ?? ''}
placeholder="Photographer credit"
onChange={(e) => patchIptc('credit', e.target.value)}
disabled={!onUpdate}
/>
</label>
<label className="field">
<span>Source</span>
<input
value={photo.iptc?.source ?? ''}
placeholder="Agency or client"
onChange={(e) => patchIptc('source', e.target.value)}
disabled={!onUpdate}
/>
</label>
</div>
<div className="field-row">
<label className="field">
<span>City</span>
<input
value={photo.iptc?.city ?? ''}
placeholder="City"
onChange={(e) => patchIptc('city', e.target.value)}
disabled={!onUpdate}
/>
</label>
<label className="field">
<span>Country</span>
<input
value={photo.iptc?.country ?? ''}
placeholder="Country"
onChange={(e) => patchIptc('country', e.target.value)}
disabled={!onUpdate}
/>
</label>
</div>
<div className="metadata-presets"> <div className="metadata-presets">
<select value={presetId} onChange={(e) => applyPreset(e.target.value)} disabled={!presets.length || !onUpdate}> <select value={presetId} onChange={(e) => applyPreset(e.target.value)} disabled={!presets.length || !onUpdate}>
<option value="">Apply metadata preset…</option> <option value="">Apply metadata preset…</option>
+69 -8
View File
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { normalizeEdits } from '../lib/edits'; import { applyPresetEdits } from '../lib/presets';
import { get16BitSource, getBitmap } from '../lib/images'; import { get16BitSource, getBitmap } from '../lib/images';
import { Renderer, rotatedBounds } from '../gl/renderer'; import { Renderer, rotatedBounds } from '../gl/renderer';
import type { PhotoRecord, Preset } from '../types'; import type { PhotoRecord, Preset } from '../types';
@@ -17,17 +17,66 @@ const THUMB_EDGE = 200;
const keyOf = (photoId: string, presetId: string, crop: string, source: string) => const keyOf = (photoId: string, presetId: string, crop: string, source: string) =>
`${photoId}|${presetId}|${crop}|${source}`; `${photoId}|${presetId}|${crop}|${source}`;
/** Stringified grades, cached per edits object so a render loop cannot make this
* cost more than one serialisation. */
const signatures = new WeakMap<object, string>();
function gradeSignature(edits: object): string {
let sig = signatures.get(edits);
if (sig === undefined) {
sig = JSON.stringify(edits);
signatures.set(edits, sig);
}
return sig;
}
/**
* A slider drag produces a new grade every frame. Re-rendering the whole rail
* that often would make the canvas stutter, so the tiles follow the grade a
* moment after it settles.
*
* The timer is keyed on the grade's signature, not on the object: the editor can
* hand down a fresh edits object on every render, and an identity-keyed timer
* would then be reset forever and the rail would never catch up.
*/
function useSettledEdits<T extends object>(edits: T, sig: string, delay: number): T {
const [settled, setSettled] = useState(() => ({ sig, edits }));
useEffect(() => {
if (sig === settled.sig) return;
const timer = window.setTimeout(() => setSettled({ sig, edits }), delay);
return () => window.clearTimeout(timer);
// `edits` is read from the render that changed the signature; restarting on
// a new object with the same grade is exactly what this avoids.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sig, delay, settled.sig]);
return settled.edits;
}
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> { export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
const [thumbs, setThumbs] = useState<Record<string, string>>({}); const [thumbs, setThumbs] = useState<Record<string, string>>({});
// Which photo the thumbnails in state belong to; a new photo may not reuse them.
const shownPhoto = useRef(photo.id);
// Preset edits never change after creation, so a stable id list is enough to // Preset edits never change after creation, so a stable id list is enough to
// avoid re-running for every parent render. // avoid re-running for every parent render.
const presetKey = presets.map((p) => p.id).join('|'); const presetKey = presets.map((p) => p.id).join('|');
const crop = photo.edits.crop; // Tiles show the look over the grade the photo has right now, so clicking one
// is what the thumbnail promised. The grade is read once it settles instead of
// on every frame of a slider drag.
const settled = useSettledEdits(photo.edits, gradeSignature(photo.edits), 280);
// Applying a look replaces any cast the last one added, so the current look is
// dropped from the base: tiles keep their images while the photographer clicks
// through looks, and each tile still shows what that click would produce.
const base =
settled.presetLook && (settled.presetLook.temp || settled.presetLook.tint)
? { ...settled, presetLook: { temp: 0, tint: 0 } }
: settled;
const crop = base.crop;
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(','); const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
// The preset previews keep the photo's camera profile, so a reprocess or a // The preset previews keep the photo's camera profile, so a reprocess or a
// different profile has to invalidate tiles the same way a crop does. // different profile has to invalidate the tiles the same way the grade does.
const profile = photo.edits.cameraProfile; const profile = base.cameraProfile;
const sourceKey = `${photo.previewVersion ?? 0}|${profile ? profile.matrix.join(',') : ''}`; const gradeKey = JSON.stringify({ ...base, crop: undefined, cameraProfile: undefined });
const sourceKey = `${photo.previewVersion ?? 0}|${profile ? profile.matrix.join(',') : ''}|${gradeKey}`;
useEffect(() => { useEffect(() => {
let alive = true; let alive = true;
@@ -39,7 +88,19 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
const hit = cache.get(keyOf(photo.id, preset.id, cropKey, sourceKey)); const hit = cache.get(keyOf(photo.id, preset.id, cropKey, sourceKey));
if (hit) known[preset.id] = hit; if (hit) known[preset.id] = hit;
} }
setThumbs(known); // Keep the previous tiles of this photo on screen until their replacements
// render: a grade change must not empty the rail for the five seconds a full
// batch takes.
const samePhoto = shownPhoto.current === photo.id;
shownPhoto.current = photo.id;
setThumbs((prev) => {
const next: Record<string, string> = {};
for (const preset of presets) {
const url = known[preset.id] ?? (samePhoto ? prev[preset.id] : undefined);
if (url) next[preset.id] = url;
}
return next;
});
const pending = presets.filter((p) => !known[p.id]); const pending = presets.filter((p) => !known[p.id]);
if (!pending.length) return; if (!pending.length) return;
@@ -63,7 +124,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
for (const preset of pending) { for (const preset of pending) {
if (!alive) break; if (!alive) break;
try { try {
renderer.render({ ...normalizeEdits(preset.edits), crop, cameraProfile: profile }, { renderer.render(applyPresetEdits(base, preset), {
width, width,
height, height,
upscale: Math.max(width / cropW, height / cropH) > 1.05, upscale: Math.max(width / cropW, height / cropH) > 1.05,
+8
View File
@@ -1,4 +1,5 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import { APP_VERSION, GUIDE_UPDATED, GUIDE_VERSION } from '../lib/about';
const GROUPS: { title: string; rows: [string, string][] }[] = [ const GROUPS: { title: string; rows: [string, string][] }[] = [
{ {
@@ -96,6 +97,13 @@ export default function Shortcuts({ onClose }: { onClose: () => void }) {
<p>Hover a panel seam to reveal its collapse tab. Press Tab to move focus, or ? for this list.</p> <p>Hover a panel seam to reveal its collapse tab. Press Tab to move focus, or ? for this list.</p>
<p>⌘K / Ctrl+K searches the whole catalog without changing your current filters.</p> <p>⌘K / Ctrl+K searches the whole catalog without changing your current filters.</p>
</section> </section>
<section className="shortcut-start shortcut-about">
<h3>About Luminary</h3>
<p>
Version {APP_VERSION} · Beta · user guide {GUIDE_VERSION}, updated {GUIDE_UPDATED}.
</p>
<p>Click the Luminary name in the top bar for the full About panel and the PDF guide.</p>
</section>
</div> </div>
</div> </div>
</div> </div>
+17 -2
View File
@@ -3,7 +3,7 @@ import type { Preview16 } from '../lib/preview16';
import type { CurvePoint, Edits, GeometryEdits, LocalLayer } from '../types'; import type { CurvePoint, Edits, GeometryEdits, LocalLayer } from '../types';
import { buildSampler, clamp01 } from '../lib/curves'; import { buildSampler, clamp01 } from '../lib/curves';
import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits'; import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits';
import { wbGainFor } from '../lib/whiteBalance'; import { wbGainWithLook } from '../lib/whiteBalance';
import { buildLocalMasks, maskSignature } from './masks'; import { buildLocalMasks, maskSignature } from './masks';
import { getActiveProofCube, type SoftProofCube } from '../lib/softProof'; import { getActiveProofCube, type SoftProofCube } from '../lib/softProof';
@@ -1875,7 +1875,9 @@ export class Renderer {
g.f('u_srcLod', Math.max(0, Math.min(12, srcLod))); g.f('u_srcLod', Math.max(0, Math.min(12, srcLod)));
g.f('u_pick', -1); g.f('u_pick', -1);
g.v2('u_pickUv', 0, 0); g.v2('u_pickUv', 0, 0);
const wb = wbGainFor(edits.temp, edits.tint, edits.kelvin); // The photographer's correction is the base; an applied look only adds its
// cast on top of it (see applyPresetEdits).
const wb = wbGainWithLook(edits.temp, edits.tint, edits.kelvin, edits.presetLook);
g.v3('u_wbGain', wb[0], wb[1], wb[2]); g.v3('u_wbGain', wb[0], wb[1], wb[2]);
g.f('u_exposure', edits.exposure); g.f('u_exposure', edits.exposure);
g.f('u_recovery', edits.recovery); g.f('u_recovery', edits.recovery);
@@ -2011,6 +2013,12 @@ export class Renderer {
lens?: LensCorrection | null; lens?: LensCorrection | null;
/** 0–1 screen split: left is uncorrected, right is corrected. */ /** 0–1 screen split: left is uncorrected, right is corrected. */
lensSplit?: number; lensSplit?: number;
/**
* Draw only this horizontal slice of the canvas, in device pixels. The
* before/after split renders the edit full-frame, then the untouched
* source over the left side, so both halves share one view and line up.
*/
scissor?: { x: number; w: number };
/** hold the grain pattern still, e.g. while a crop handle is being dragged */ /** hold the grain pattern still, e.g. while a crop handle is being dragged */
freezeGrain?: boolean; freezeGrain?: boolean;
/** paint clipped channels while the exposure control is being dragged */ /** paint clipped channels while the exposure control is being dragged */
@@ -2137,6 +2145,12 @@ export class Renderer {
// Pass 4: detail, effects, grain -> canvas // Pass 4: detail, effects, grain -> canvas
const finishDraw = (target: Target | null, clip = 0) => { const finishDraw = (target: Target | null, clip = 0) => {
const gl2 = this.gl; const gl2 = this.gl;
// Render targets are always complete frames; only the canvas is ever cut.
const scissor = target ? undefined : opts.scissor;
if (scissor) {
gl2.enable(gl2.SCISSOR_TEST);
gl2.scissor(scissor.x, 0, Math.max(1, scissor.w), h);
}
if (target) { if (target) {
gl2.bindFramebuffer(gl2.FRAMEBUFFER, target.fbo); gl2.bindFramebuffer(gl2.FRAMEBUFFER, target.fbo);
gl2.viewport(0, 0, target.w, target.h); gl2.viewport(0, 0, target.w, target.h);
@@ -2213,6 +2227,7 @@ export class Renderer {
this.finish.v2('u_outSize', target ? target.w : w, target ? target.h : h); this.finish.v2('u_outSize', target ? target.w : w, target ? target.h : h);
this.finish.f('u_aspect', w / h); this.finish.f('u_aspect', w / h);
this.drawQuad(); this.drawQuad();
if (scissor) gl2.disable(gl2.SCISSOR_TEST);
}; };
const clipMode = opts.clipPreview const clipMode = opts.clipPreview
+6 -3
View File
@@ -1,7 +1,10 @@
/** /**
* Versions shown in the About panel. APP_VERSION mirrors package.json; the * Versions shown in the About panel. APP_VERSION comes straight from
* guide values are bumped when docs/user-guide/guide.html is republished. * package.json, so the UI cannot report a version the release did not ship.
* Bump the guide values when docs/user-guide/guide.html is republished.
*/ */
export const APP_VERSION = '0.5.1'; import { version as APP_VERSION } from '../../package.json';
export { APP_VERSION };
export const GUIDE_VERSION = '0.5'; export const GUIDE_VERSION = '0.5';
export const GUIDE_UPDATED = 'November 2026'; export const GUIDE_UPDATED = 'November 2026';
+40 -4
View File
@@ -35,6 +35,17 @@ export interface UploadResult {
note?: string | null; note?: string | null;
} }
/**
* True once /api/health reports LUMINARY_LOCAL=1: the engine runs inside this
* app's own folder, so copy must not send users looking for a remote server.
*/
let localEngine = false;
/** Whether this app talks to the engine in its own bundle (desktop mode). */
export function isLocalEngine(): boolean {
return localEngine;
}
export class ApiError extends Error { export class ApiError extends Error {
status: number; status: number;
constructor(message: string, status: number) { constructor(message: string, status: number) {
@@ -48,7 +59,10 @@ export async function request<T>(path: string, init?: RequestInit): Promise<T> {
try { try {
res = await fetch(path, { credentials: 'same-origin', ...init }); res = await fetch(path, { credentials: 'same-origin', ...init });
} catch { } catch {
throw new ApiError('Cannot reach the Luminary server', 0); throw new ApiError(
localEngine ? 'Cannot reach the Luminary local engine' : 'Cannot reach the Luminary server',
0,
);
} }
if (!res.ok) { if (!res.ok) {
let message = `Request failed (${res.status})`; let message = `Request failed (${res.status})`;
@@ -78,6 +92,7 @@ export async function getHealth(): Promise<Health | null> {
const res = await fetch('/api/health', { credentials: 'same-origin' }); const res = await fetch('/api/health', { credentials: 'same-origin' });
if (!res.ok) return null; if (!res.ok) return null;
const body = (await res.json()) as Health; const body = (await res.json()) as Health;
localEngine = body?.local === true;
return body?.ok ? body : null; return body?.ok ? body : null;
} catch { } catch {
return null; return null;
@@ -140,8 +155,16 @@ export function pullProofs(): Promise<ProofSummary[]> {
return request<{ proofs: ProofSummary[] }>('/api/proofs').then((res) => res.proofs ?? []); return request<{ proofs: ProofSummary[] }>('/api/proofs').then((res) => res.proofs ?? []);
} }
export function uploadOriginal(id: string, file: File | Blob, name: string): Promise<UploadResult> { export function uploadOriginal(
id: string,
file: File | Blob,
name: string,
options: { sidecar?: boolean } = {},
): Promise<UploadResult> {
const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' }); const query = new URLSearchParams({ name, mime: file.type || 'application/octet-stream' });
// Only an opt-out is sent: an older server ignores the parameter and keeps
// its configured default, and every other upload keeps the shorter URL.
if (options.sidecar === false) query.set('sidecar', '0');
return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, { return request<UploadResult>(`/api/photos/${encodeURIComponent(id)}/original?${query}`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' }, headers: { 'Content-Type': 'application/octet-stream' },
@@ -180,6 +203,13 @@ export interface ProofUpload {
} }
/** Upload a rendered (edited) proof for the client gallery and owner grid. */ /** Upload a rendered (edited) proof for the client gallery and owner grid. */
export interface DenoiseProgress {
stage: 'analyse' | 'base' | 'gate' | 'render';
/** Tile counter, present while the base model is running. */
done?: number;
total?: number;
}
export interface DenoiseJob { export interface DenoiseJob {
id: string; id: string;
key: string; key: string;
@@ -187,14 +217,20 @@ export interface DenoiseJob {
ms: number | null; ms: number | null;
error: string | null; error: string | null;
url: string | null; url: string | null;
/** Where the worker is inside the run; null once it finishes. */
progress?: DenoiseProgress | null;
/** Reported by a job that found the render already on disk. */ /** Reported by a job that found the render already on disk. */
cached?: boolean; cached?: boolean;
stats: { amount: number; autoGate: number; gate: number; noise: number; baseWidth: number } | null; stats: { amount: number; autoGate: number; gate: number; noise: number; baseWidth: number } | null;
} }
/** Starts a server-side denoise job; the work runs off the request thread. */ /** Starts a server-side denoise job; the work runs off the request thread. */
export function startDenoise(photoId: string): Promise<{ jobId: string }> { export function startDenoise(photoId: string, base: 'guided' | 'nlm' | 'scunet' = 'guided'): Promise<{ jobId: string }> {
return request(`/api/photos/${encodeURIComponent(photoId)}/denoise`, { method: 'POST' }); return request(`/api/photos/${encodeURIComponent(photoId)}/denoise`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ base }),
});
} }
/** Drops the rendered files for a photo; the next run renders from scratch. */ /** Drops the rendered files for a photo; the next run renders from scratch. */
+84
View File
@@ -0,0 +1,84 @@
import { describe, expect, it } from 'vitest';
import { defaultEdits, normalizeEdits } from './edits';
import {
DENOISE_MODELS,
denoiseModelLabel,
denoiseProgressLabel,
withDenoiseRender,
} from './denoiseModels';
describe('AI denoise edit normalization', () => {
it('keeps the model the user picked', () => {
for (const model of ['guided', 'scunet', 'nlm'] as const) {
expect(normalizeEdits({ aiDenoise: { model } } as never).aiDenoise.model).toBe(model);
}
});
it('defaults an unknown or missing model to guided', () => {
expect(normalizeEdits({}).aiDenoise.model).toBe('guided');
expect(normalizeEdits({ aiDenoise: {} } as never).aiDenoise.model).toBe('guided');
expect(normalizeEdits({ aiDenoise: { model: 'swinir' } } as never).aiDenoise.model).toBe(
'guided',
);
});
it('keeps the render key and the amount, and drops an unusable key', () => {
const kept = normalizeEdits({ aiDenoise: { model: 'nlm', key: 'abc123', amount: 40 } } as never);
expect(kept.aiDenoise).toEqual({ model: 'nlm', key: 'abc123', amount: 40 });
const dropped = normalizeEdits({ aiDenoise: { key: '' } } as never);
expect(dropped.aiDenoise.key).toBeNull();
});
});
describe('AI denoise model selection', () => {
it('commits the render under the base that produced it', () => {
// The regression: the panel's completion path used to spread a copy of the
// edit captured before the chip click, which put the previous model back.
const previous = { ...defaultEdits().aiDenoise, model: 'guided' as const, amount: 70 };
const next = withDenoiseRender(previous, 'scunet', 'key-scunet');
expect(next).toEqual({ model: 'scunet', key: 'key-scunet', amount: 70 });
expect(previous).toEqual({ model: 'guided', key: null, amount: 70 });
});
it('keeps a stale picker honest for every base', () => {
const previous = { ...defaultEdits().aiDenoise, model: 'guided' as const };
for (const option of DENOISE_MODELS) {
expect(withDenoiseRender(previous, option.value, `key-${option.value}`).model).toBe(
option.value,
);
}
});
it('names the stage and tile count a running render reports', () => {
expect(denoiseProgressLabel({ stage: 'base', done: 12, total: 40 }, 'scunet', 31)).toBe(
'Rendering with SCUNet · denoising 12/40 tiles · 31s elapsed',
);
expect(denoiseProgressLabel({ stage: 'gate' }, 'guided', 7.4)).toBe(
'Rendering with Guided · mapping detail · 7s elapsed',
);
// No tile counter for the classical models, and no stage at all before the
// first poll lands.
expect(denoiseProgressLabel({ stage: 'base' }, 'nlm', 2)).toBe(
'Rendering with NLM · denoising · 2s elapsed',
);
expect(denoiseProgressLabel(null, 'scunet', 0)).toBe(
'Rendering with SCUNet · starting · 0s elapsed',
);
// A worker that over-counts cannot report past the end of the run.
expect(denoiseProgressLabel({ stage: 'base', done: 99, total: 40 }, 'scunet', 90)).toContain(
'40/40 tiles',
);
});
it('offers each selectable model exactly once, with a label', () => {
const values = DENOISE_MODELS.map((option) => option.value);
expect(new Set(values).size).toBe(values.length);
expect(values).toEqual(['guided', 'scunet', 'nlm']);
for (const option of DENOISE_MODELS) {
expect(option.label, option.value).toBeTruthy();
expect(option.title, option.value).toBeTruthy();
expect(denoiseModelLabel(option.value)).toBe(option.label);
}
});
});
+57
View File
@@ -0,0 +1,57 @@
import type { DenoiseProgress } from './api';
import type { Edits } from '../types';
/** One of the base denoisers the AI denoise panel can render with. */
export type DenoiseModel = Edits['aiDenoise']['model'];
export type AiDenoise = Edits['aiDenoise'];
/**
* The models in panel order. `guided` is the default and the fast one; the two
* learned/classical alternates are additive, so the list is also the contract
* the picker and the help text are built from.
*/
export const DENOISE_MODELS: { value: DenoiseModel; label: string; title: string }[] = [
{ value: 'guided', label: 'Guided', title: 'Guided filter — fast, keeps the most fine texture' },
{ value: 'scunet', label: 'SCUNet', title: 'SCUNet — learned model, removes the most grain, smooths more' },
{ value: 'nlm', label: 'NLM', title: 'Non-local means — slower, between Guided and SCUNet' },
];
export function denoiseModelLabel(model: DenoiseModel): string {
return DENOISE_MODELS.find((option) => option.value === model)?.label ?? 'Guided';
}
/** Human names for the pipeline stages the worker reports. */
const STAGE_LABELS: Record<DenoiseProgress['stage'], string> = {
analyse: 'reading the noise profile',
base: 'denoising',
gate: 'mapping detail',
render: 'blending the result',
};
/**
* One line describing a running render. The stage names and the tile counter
* come from the worker, so this is real progress rather than a spinner -- the
* elapsed time is only the fallback for the first second or two.
*/
export function denoiseProgressLabel(
progress: DenoiseProgress | null | undefined,
model: DenoiseModel,
elapsedSeconds: number,
): string {
const seconds = Math.max(0, Math.round(elapsedSeconds));
const stage = progress?.stage ? (STAGE_LABELS[progress.stage] ?? 'working') : 'starting';
const tiles =
progress?.stage === 'base' && progress.total
? ` ${Math.min(progress.done ?? 0, progress.total)}/${progress.total} tiles`
: '';
return `Rendering with ${denoiseModelLabel(model)} · ${stage}${tiles} · ${seconds}s elapsed`;
}
/**
* Commit a finished render to the edit. The cache key belongs to the base that
* produced it, so the picker follows that base: a caller holding an older copy
* of the edit cannot put the previous model back in front of a fresh key.
*/
export function withDenoiseRender(ai: AiDenoise, base: DenoiseModel, key: string): AiDenoise {
return { ...ai, model: base, key };
}
+1
View File
@@ -82,6 +82,7 @@ const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
'temp', 'temp',
'tint', 'tint',
'kelvin', 'kelvin',
'presetLook',
'exposure', 'exposure',
'recovery', 'recovery',
'contrast', 'contrast',
+41 -1
View File
@@ -11,6 +11,7 @@ import type {
LocalMaskKind, LocalMaskKind,
LocalPoint, LocalPoint,
LocalStroke, LocalStroke,
IptcFields,
LensCorrections, LensCorrections,
LensProfile, LensProfile,
RasterMask, RasterMask,
@@ -177,6 +178,7 @@ export function defaultEdits(): Edits {
temp: 0, temp: 0,
tint: 0, tint: 0,
kelvin: null, kelvin: null,
presetLook: { temp: 0, tint: 0 },
exposure: 0, exposure: 0,
recovery: 0, recovery: 0,
contrast: 0, contrast: 0,
@@ -500,7 +502,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
aiDenoise: { aiDenoise: {
amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100), amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100),
key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null, key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null,
model: 'guided', model:
aiDenoise.model === 'guided' || aiDenoise.model === 'nlm' || aiDenoise.model === 'scunet'
? aiDenoise.model
: 'guided',
}, },
temp: num(input.temp, 0, -100, 100), temp: num(input.temp, 0, -100, 100),
tint: num(input.tint, 0, -100, 100), tint: num(input.tint, 0, -100, 100),
@@ -508,6 +513,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
typeof input.kelvin === 'number' && Number.isFinite(input.kelvin) typeof input.kelvin === 'number' && Number.isFinite(input.kelvin)
? clamp(input.kelvin, 1500, 15000) ? clamp(input.kelvin, 1500, 15000)
: null, : null,
presetLook: {
temp: num(input.presetLook?.temp, 0, -100, 100),
tint: num(input.presetLook?.tint, 0, -100, 100),
},
exposure: num(input.exposure, 0, -5, 5), exposure: num(input.exposure, 0, -5, 5),
recovery: num(input.recovery, 0, 0, 100), recovery: num(input.recovery, 0, 0, 100),
contrast: num(input.contrast, 0, -100, 100), contrast: num(input.contrast, 0, -100, 100),
@@ -635,6 +644,31 @@ export function isEdited(edits: Edits): boolean {
return result; return result;
} }
/** Trimmed, capped strings only: IPTC goes into files, so no objects or arrays. */
function textField(value: unknown, max: number): string | undefined {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
return trimmed ? trimmed.slice(0, max) : undefined;
}
function sanitiseIptc(input: unknown): IptcFields | undefined {
if (!input || typeof input !== 'object') return undefined;
const raw = input as Record<string, unknown>;
const fields: IptcFields = {
headline: textField(raw.headline, 256),
credit: textField(raw.credit, 128),
source: textField(raw.source, 128),
city: textField(raw.city, 128),
state: textField(raw.state, 128),
country: textField(raw.country, 128),
location: textField(raw.location, 128),
};
const kept = Object.fromEntries(
Object.entries(fields).filter(([, value]) => value !== undefined),
) as IptcFields;
return Object.keys(kept).length > 0 ? kept : undefined;
}
export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord { export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord {
const edits = normalizeEdits(input.edits); const edits = normalizeEdits(input.edits);
const addedAt = input.addedAt ?? Date.now(); const addedAt = input.addedAt ?? Date.now();
@@ -690,6 +724,12 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
flag: (input.flag ?? 'none') as Flag, flag: (input.flag ?? 'none') as Flag,
color: (input.color ?? '') as ColorLabel, color: (input.color ?? '') as ColorLabel,
keywords: Array.isArray(input.keywords) ? input.keywords : [], keywords: Array.isArray(input.keywords) ? input.keywords : [],
keywordPaths: Array.isArray(input.keywordPaths)
? input.keywordPaths.filter(
(path): path is string => typeof path === 'string' && path.trim().length > 0,
).slice(0, 200)
: undefined,
iptc: sanitiseIptc(input.iptc),
edits, edits,
history: history:
Array.isArray(input.history) && input.history.length Array.isArray(input.history) && input.history.length
+8
View File
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { outputSize } from '../gl/renderer'; import { outputSize } from '../gl/renderer';
import { defaultEdits } from './edits'; import { defaultEdits } from './edits';
import { buildFileName, DEFAULT_EXPORT } from './export';
import type { PhotoRecord } from '../types';
describe('export output dimensions', () => { describe('export output dimensions', () => {
it('matches the source for an uncropped image', () => { it('matches the source for an uncropped image', () => {
@@ -19,6 +21,12 @@ describe('export output dimensions', () => {
expect(outputSize(edits, 4000, 3000)).toEqual({ w: 4950, h: 4950 }); expect(outputSize(edits, 4000, 3000)).toEqual({ w: 4950, h: 4950 });
}); });
it('writes the JPEG XL extension for a JXL export', () => {
const photo = { name: 'DSCF1234.RAF', addedAt: Date.now() } as PhotoRecord;
const name = buildFileName('{name}', photo, 0, { ...DEFAULT_EXPORT, format: 'jxl' });
expect(name).toBe('DSCF1234.jxl');
});
it('applies the crop after the rotated frame is calculated', () => { it('applies the crop after the rotated frame is calculated', () => {
const edits = defaultEdits(); const edits = defaultEdits();
edits.crop.angle = 45; edits.crop.angle = 45;
+41 -12
View File
@@ -1,6 +1,7 @@
import type { Edits, PhotoRecord } from '../types'; import type { Edits, PhotoRecord } from '../types';
import { get16BitSource, getBitmap } from './images'; import { get16BitSource, getBitmap } from './images';
import { normalizeEdits } from './edits'; import { normalizeEdits } from './edits';
import { photoMetadataAttributes, photoMetadataElements } from './xmp';
import { buildLensCorrection } from './lensEngine'; import { buildLensCorrection } from './lensEngine';
import { outputSize, Renderer } from '../gl/renderer'; import { outputSize, Renderer } from '../gl/renderer';
import { getDenoisedBitmap } from './images'; import { getDenoisedBitmap } from './images';
@@ -8,8 +9,9 @@ import { createZipBlob, zipFileName } from './zip';
import { profileFor, type OutputColorSpace } from './icc'; import { profileFor, type OutputColorSpace } from './icc';
import { convertFloatPixels, convertImageData } from './colorSpace'; import { convertFloatPixels, convertImageData } from './colorSpace';
import { encodeTiff16 } from './tiff'; import { encodeTiff16 } from './tiff';
import { encodeJxl } from './jxl';
export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16'; export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16' | 'jxl';
export type ResizeMode = 'none' | 'longEdge' | 'percent'; export type ResizeMode = 'none' | 'longEdge' | 'percent';
export type WatermarkPosition = 'br' | 'bl' | 'tr' | 'tl' | 'center'; export type WatermarkPosition = 'br' | 'bl' | 'tr' | 'tl' | 'center';
@@ -27,6 +29,8 @@ export interface ExportOptions {
zip: boolean; zip: boolean;
/** Extra capture sharpening applied only to the exported pixels. */ /** Extra capture sharpening applied only to the exported pixels. */
outputSharpen: number; outputSharpen: number;
/** JPEG XL only: keep every pixel instead of using the quality slider. */
jxlLossless?: boolean;
/** Write title/caption/creator/copyright/keywords into the file. */ /** Write title/caption/creator/copyright/keywords into the file. */
metadata: boolean; metadata: boolean;
/** Embed the generated sRGB ICC profile in JPEG/TIFF files. */ /** Embed the generated sRGB ICC profile in JPEG/TIFF files. */
@@ -56,6 +60,7 @@ export const DEFAULT_EXPORT: ExportOptions = {
nameTemplate: '{name}', nameTemplate: '{name}',
zip: true, zip: true,
outputSharpen: 0, outputSharpen: 0,
jxlLossless: false,
metadata: true, metadata: true,
embedProfile: true, embedProfile: true,
watermark: { enabled: false, text: '', position: 'br', opacity: 55, size: 4 }, watermark: { enabled: false, text: '', position: 'br', opacity: 55, size: 4 },
@@ -66,6 +71,7 @@ const MIME: Record<ExportFormat, string> = {
png: 'image/png', png: 'image/png',
webp: 'image/webp', webp: 'image/webp',
tiff16: 'image/tiff', tiff16: 'image/tiff',
jxl: 'image/jxl',
}; };
const EXT: Record<ExportFormat, string> = { const EXT: Record<ExportFormat, string> = {
@@ -73,6 +79,7 @@ const EXT: Record<ExportFormat, string> = {
png: 'png', png: 'png',
webp: 'webp', webp: 'webp',
tiff16: 'tif', tiff16: 'tif',
jxl: 'jxl',
}; };
function download(blob: Blob, filename: string) { function download(blob: Blob, filename: string) {
@@ -178,6 +185,12 @@ export async function renderPhotoBlob(
if (opts.watermark.enabled && opts.watermark.text.trim()) { if (opts.watermark.enabled && opts.watermark.text.trim()) {
output = paintWatermark(output, photo, opts); output = paintWatermark(output, photo, opts);
} }
if (opts.format === 'jxl') {
return encodeJxl(readPixels(output), {
quality: opts.quality,
lossless: opts.jxlLossless === true,
});
}
const mime = MIME[opts.format]; const mime = MIME[opts.format];
let blob = await new Promise<Blob | null>((resolve) => let blob = await new Promise<Blob | null>((resolve) =>
output.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))), output.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))),
@@ -197,6 +210,20 @@ export async function renderPhotoBlob(
} }
} }
/**
* The render canvas holds a WebGL context, so its pixels have to be drawn into
* a 2D canvas before an encoder can read them.
*/
function readPixels(source: HTMLCanvasElement): ImageData {
const canvas = document.createElement('canvas');
canvas.width = source.width;
canvas.height = source.height;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) throw new Error('Could not read the export pixels');
ctx.drawImage(source, 0, 0);
return ctx.getImageData(0, 0, canvas.width, canvas.height);
}
function convertCanvas(source: HTMLCanvasElement, space: OutputColorSpace) { function convertCanvas(source: HTMLCanvasElement, space: OutputColorSpace) {
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
canvas.width = source.width; canvas.width = source.width;
@@ -246,18 +273,20 @@ function paintWatermark(source: HTMLCanvasElement, photo: PhotoRecord, opts: Exp
return canvas; return canvas;
} }
function xmlEscape(value: string) { /**
return value * The XMP packet embedded in an exported file.
.replace(/&/g, '&amp;') *
.replace(/</g, '&lt;') * Built from the same helpers the sidecar writer uses, so a JPEG and its .xmp
.replace(/>/g, '&gt;') * cannot drift: rating, colour label, keywords, the `lr:` hierarchy and the
.replace(/"/g, '&quot;'); * IPTC core all travel with the file.
} */
function buildXmp(photo: PhotoRecord) { function buildXmp(photo: PhotoRecord) {
const title = photo.title || photo.name; return `<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:Iptc4xmpCore="http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:lr="http://ns.adobe.com/lightroom/1.0/"${photoMetadataAttributes(
const keywords = photo.keywords.map((word) => `<rdf:li>${xmlEscape(word)}</rdf:li>`).join(''); photo,
return `<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/"><dc:title><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(title)}</rdf:li></rdf:Alt></dc:title><dc:description><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.caption ?? '')}</rdf:li></rdf:Alt></dc:description><dc:creator><rdf:Seq><rdf:li>${xmlEscape(photo.creator ?? '')}</rdf:li></rdf:Seq></dc:creator><dc:rights><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.copyright ?? '')}</rdf:li></rdf:Alt></dc:rights><dc:subject><rdf:Bag>${keywords}</rdf:Bag></dc:subject></rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`.slice(0, 65000); )}>${photoMetadataElements(photo)}</rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`.slice(
0,
65000,
);
} }
function appSegment(marker: number, header: Uint8Array, payload: Uint8Array): Uint8Array | null { function appSegment(marker: number, header: Uint8Array, payload: Uint8Array): Uint8Array | null {
+118 -22
View File
@@ -10,6 +10,8 @@ export interface ImportProgress {
done: number; done: number;
total: number; total: number;
current: string; current: string;
/** Files that have not started yet, so a long queue reads as working. */
waiting?: number;
} }
export interface ImportResult { export interface ImportResult {
@@ -20,13 +22,44 @@ export interface ImportResult {
/** Provided by the app when a Luminary server is connected. */ /** Provided by the app when a Luminary server is connected. */
export interface CloudImport { export interface CloudImport {
uploadOriginal: (id: string, file: File, name: string) => Promise<UploadResult>; uploadOriginal: (
id: string,
file: File,
name: string,
options?: { sidecar?: boolean },
) => Promise<UploadResult>;
push: (photo: PhotoRecord) => Promise<PhotoRecord>; push: (photo: PhotoRecord) => Promise<PhotoRecord>;
} }
/** Files imported at once; the server bounds how many raws decode in parallel. */ export interface ImportOptions {
/**
* Keep the 16-bit sidecar for raws in this import. On by default: the editor
* grades the decoded samples instead of 256-level JPEG pixels. Turning it off
* makes each raw import smaller and quicker, at the cost of an 8-bit grade.
*/
sidecar16?: boolean;
}
/** Files imported at once when a Luminary server is connected. */
const IMPORT_CONCURRENCY = 4; const IMPORT_CONCURRENCY = 4;
/**
* Raws and TIFFs are decoded by the server, which is where the work piles up, so
* this window is about one thing: how long a single upload request stays open.
*
* Measured on a 12-core server with 40 MP X-Trans RAFs through the real decode
* path: one file 28.4 s, two at once 44.4-45.4 s each, four at once 87.4-102.4 s
* each. Parallel X-Trans decodes barely scale here, so four-wide made every
* request about 1.5 minutes long and still finished sixteen files slower than
* two-wide (about 410 s against 360 s). Anything sitting in front of the server
* with a 60 s read timeout - the nginx default - answers 504 while the origin
* carries on decoding, which looks like a failed import of the files that were
* still in flight. Two keeps a request at ~45 s and is faster overall; Bayer
* files lose a little (8 NEFs took 20.8 s two at a time, 17.4 s four at a time)
* in exchange for every raw import staying inside a proxy's patience.
*/
const RAW_IMPORT_CONCURRENCY = 2;
export function uid(): string { export function uid(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID(); if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`; return `p_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
@@ -44,6 +77,31 @@ function mapLimit<T>(items: T[], limit: number, fn: (item: T, index: number) =>
return Promise.all(runners); return Promise.all(runners);
} }
/**
* A counting semaphore. `acquire()` resolves with a release function, so a slot
* is returned even when the guarded work throws or the import is cancelled.
* Waiters are served in order.
*/
function createSemaphore(slots: number) {
let free = Math.max(1, slots);
const waiting: (() => void)[] = [];
return {
async acquire(): Promise<() => void> {
if (free > 0) free -= 1;
else await new Promise<void>((resolve) => waiting.push(resolve));
let released = false;
return () => {
if (released) return;
released = true;
const next = waiting.shift();
// Hand the slot straight over, so it is never briefly up for grabs.
if (next) next();
else free += 1;
};
},
};
}
function formatShutter(time: unknown): string | undefined { function formatShutter(time: unknown): string | undefined {
if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined; if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return undefined;
if (time >= 1) return `${Math.round(time * 10) / 10}s`; if (time >= 1) return `${Math.round(time * 10) / 10}s`;
@@ -127,9 +185,10 @@ async function importRaw(
defaults: CameraLensDefault[], defaults: CameraLensDefault[],
/** TIFF goes through the same proxy path but is not a raw container. */ /** TIFF goes through the same proxy path but is not a raw container. */
raw = true, raw = true,
sidecar16 = true,
): Promise<PhotoRecord> { ): Promise<PhotoRecord> {
const id = uid(); const id = uid();
const upload = await cloud.uploadOriginal(id, file, file.name); const upload = await cloud.uploadOriginal(id, file, file.name, { sidecar: sidecar16 });
const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`; const previewUrl = upload.previewUrl ?? `/api/photos/${id}/preview`;
const res = await fetch(previewUrl, { credentials: 'same-origin' }); const res = await fetch(previewUrl, { credentials: 'same-origin' });
if (!res.ok) throw new Error('The server could not produce a preview for this raw file'); if (!res.ok) throw new Error('The server could not produce a preview for this raw file');
@@ -137,8 +196,10 @@ async function importRaw(
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' }); const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
const thumb = await makeThumb(bitmap); const thumb = await makeThumb(bitmap);
const { meta, takenAt } = await readMeta(file); const { meta, takenAt } = await readMeta(file);
const width = upload.width ?? bitmap.width; // `??` is wrong here: the server reports 0 for a dimension it could not read,
const height = upload.height ?? bitmap.height; // and 0 is not nullish, so a failed decode produced a 0x0 catalog record.
const width = upload.width || bitmap.width;
const height = upload.height || bitmap.height;
const edits = editsForImport(meta, defaults); const edits = editsForImport(meta, defaults);
bitmap.close(); bitmap.close();
@@ -232,7 +293,9 @@ export async function importFiles(
onProgress?: (p: ImportProgress) => void, onProgress?: (p: ImportProgress) => void,
cloud?: CloudImport | null, cloud?: CloudImport | null,
signal?: AbortSignal, signal?: AbortSignal,
options: ImportOptions = {},
): Promise<ImportResult> { ): Promise<ImportResult> {
const sidecar16 = options.sidecar16 !== false;
const result: ImportResult = { photos: [], failed: [] }; const result: ImportResult = { photos: [], failed: [] };
const images = files.filter(isSupportedFile); const images = files.filter(isSupportedFile);
const total = images.length; const total = images.length;
@@ -241,27 +304,60 @@ export async function importFiles(
const collected: { index: number; photo: PhotoRecord }[] = []; const collected: { index: number; photo: PhotoRecord }[] = [];
const defaults = await loadCameraLensDefaults().catch(() => []); const defaults = await loadCameraLensDefaults().catch(() => []);
let done = 0; let done = 0;
let active = 0;
// A wide selection spends most of its time inside a narrow window: without a
// waiting count the dialog would show "4 / 16" and no sign of the other 12.
const report = (current: string) =>
onProgress?.({ done, total, current, waiting: Math.max(0, total - done - active) });
const rawSlots = createSemaphore(RAW_IMPORT_CONCURRENCY);
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => { await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
if (signal?.aborted) return; if (signal?.aborted) return;
const viaServer = isRawFile(file) || isTiffFile(file);
// Camera JPEGs and PNGs stay this wide, because the browser decodes them
// locally and they are seconds apart at worst. A raw holds one of a couple
// of server slots first, so the upload window can stay wide for the network
// while the decode window stays as narrow as the decoder pool.
const release = viaServer ? await rawSlots.acquire() : null;
try { try {
const viaServer = isRawFile(file) || isTiffFile(file); // The import may have been cancelled while this file queued for a slot.
const photo = viaServer if (signal?.aborted) return;
? cloud // Report before the work starts, not only when it finishes. A 40 MP raw
? await importRaw(file, eventId, keywords, cloud, defaults, isRawFile(file)) // takes seconds, and four of them finish together: because progress was
: (() => { // only emitted in `finally`, the bar stayed hidden until the first batch
throw new Error('Raw files need the Luminary server. Sign in, then import again.'); // completed and then jumped to 4.
})() active += 1;
: await importStandard(file, eventId, keywords, cloud, defaults); report(file.name);
collected.push({ index, photo }); try {
} catch (err) { const photo = viaServer
result.failed.push({ ? cloud
name: file.name, ? await importRaw(
reason: err instanceof Error ? err.message : 'Unsupported image format', file,
}); eventId,
keywords,
cloud,
defaults,
isRawFile(file),
sidecar16,
)
: (() => {
throw new Error('Raw files need the Luminary server. Sign in, then import again.');
})()
: await importStandard(file, eventId, keywords, cloud, defaults);
collected.push({ index, photo });
} catch (err) {
result.failed.push({
name: file.name,
reason: err instanceof Error ? err.message : 'Unsupported image format',
});
} finally {
active -= 1;
done += 1;
report(file.name);
}
} finally { } finally {
done += 1; release?.();
onProgress?.({ done, total, current: file.name });
} }
}); });
@@ -269,6 +365,6 @@ export async function importFiles(
collected.sort((a, b) => a.index - b.index); collected.sort((a, b) => a.index - b.index);
result.photos = collected.map((c) => c.photo); result.photos = collected.map((c) => c.photo);
result.cancelled = Boolean(signal?.aborted); result.cancelled = Boolean(signal?.aborted);
onProgress?.({ done: total, total, current: '' }); onProgress?.({ done: total, total, current: '', waiting: 0 });
return result; return result;
} }
+82
View File
@@ -0,0 +1,82 @@
/**
* JPEG XL export (8-bit sRGB), encoded by libjxl compiled to WebAssembly.
*
* The codec is imported on demand: it is roughly 1.4 MB of wasm plus glue, and
* most sessions never export a JXL. Only the single-threaded build is used —
* the app is not cross-origin isolated, so the multithreaded glue would fall
* back anyway, and its worker entry points cannot be bundled.
*
* The glue resolves its wasm relative to its own module URL, which a bundler
* rewrites; `locateFile` points it at the URL Vite actually emitted.
*/
import jxlWasm from '@jsquash/jxl/codec/enc/jxl_enc.wasm?url';
export interface JxlOptions {
/** 1–100, the same number the modal's quality slider shows. */
quality: number;
lossless: boolean;
}
interface JxlEncodeOptions {
effort: number;
quality: number;
lossless: boolean;
progressive: boolean;
epf: number;
lossyPalette: boolean;
decodingSpeedTier: number;
photonNoiseIso: number;
lossyModular: boolean;
}
interface JxlModule {
encode(data: BufferSource, width: number, height: number, options: JxlEncodeOptions): Uint8Array | null;
}
let encoder: Promise<JxlModule> | null = null;
function loadEncoder(): Promise<JxlModule> {
if (!encoder) {
encoder = (async () => {
const [{ default: factory }, { initEmscriptenModule }] = await Promise.all([
import('@jsquash/jxl/codec/enc/jxl_enc.js'),
import('@jsquash/jxl/utils.js'),
]);
const module = await initEmscriptenModule(factory as never, undefined, {
locateFile: (path: string) => (path.endsWith('jxl_enc.wasm') ? jxlWasm : path),
});
return module as unknown as JxlModule;
})().catch((error) => {
// A failed load must not poison every later export.
encoder = null;
throw error;
});
}
return encoder;
}
export async function encodeJxl(image: ImageData, options: JxlOptions): Promise<Blob> {
const module = await loadEncoder();
const lossless = options.lossless === true;
const quality = Math.min(100, Math.max(1, Math.round(options.quality || 90)));
const result = module.encode(image.data, image.width, image.height, {
quality: lossless ? 100 : quality,
lossless,
// libjxl defaults to effort 7, which is a long wait single-threaded on a
// 45 MP frame. 5 keeps a batch moving and costs little for photographs.
effort: 5,
progressive: false,
epf: -1,
lossyPalette: false,
decodingSpeedTier: 0,
photonNoiseIso: 0,
lossyModular: false,
});
if (!result || !result.byteLength) throw new Error('JPEG XL encoding failed');
// A fresh buffer: the encoder returns a view that may over-allocate, and a
// Blob must not keep the wasm heap alive.
const bytes = new Uint8Array(result.byteLength);
bytes.set(result);
return new Blob([bytes], { type: 'image/jxl' });
}
+99
View File
@@ -0,0 +1,99 @@
import { describe, expect, it } from 'vitest';
import {
addKeywordPath,
collectKeywordPaths,
keywordTree,
normalizeKeywordPath,
pathAncestors,
pathLeaf,
pathsUnder,
removeKeywordPath,
} from './keywords';
const empty = { keywords: [] as string[], keywordPaths: [] as string[] };
describe('keyword paths', () => {
it('normalises every separator to the Lightroom form', () => {
expect(normalizeKeywordPath('Nature>Birds>Robin')).toBe('Nature > Birds > Robin');
expect(normalizeKeywordPath('Nature/Birds / Robin ')).toBe('Nature > Birds > Robin');
expect(normalizeKeywordPath('Nature | Birds')).toBe('Nature > Birds');
expect(normalizeKeywordPath(' ')).toBe('');
});
it('reads the leaf and the ancestor chain', () => {
expect(pathLeaf('Nature > Birds > Robin')).toBe('Robin');
expect(pathAncestors('Nature > Birds > Robin')).toEqual([
'Nature',
'Nature > Birds',
'Nature > Birds > Robin',
]);
});
it('records ancestors and puts the leaf in the flat list', () => {
const next = addKeywordPath(empty, 'Nature > Birds > Robin');
expect(next.keywordPaths).toEqual([
'Nature',
'Nature > Birds',
'Nature > Birds > Robin',
]);
expect(next.keywords).toEqual(['Robin']);
});
it('keeps a plain word flat', () => {
const next = addKeywordPath(empty, 'Robin', false);
expect(next.keywords).toEqual(['Robin']);
expect(next.keywordPaths).toEqual([]);
});
it('does not duplicate on case alone', () => {
const first = addKeywordPath(empty, 'Nature > Birds');
const second = addKeywordPath(first, 'nature > birds');
expect(second.keywordPaths).toEqual(['Nature', 'Nature > Birds']);
expect(second.keywords).toEqual(['Birds']);
});
it('removes a subtree and the leaves it stranded', () => {
const full = addKeywordPath(addKeywordPath(empty, 'Nature > Birds > Robin'), 'Nature > Birds > Wren');
const next = removeKeywordPath(full, 'Nature > Birds');
expect(next.keywordPaths).toEqual(['Nature']);
// Robin and Wren came only from the removed branch, Birds was the node.
expect(next.keywords).toEqual([]);
});
it('keeps a leaf that another path still uses', () => {
const both = addKeywordPath(addKeywordPath(empty, 'Nature > Birds > Robin'), 'Garden > Robin');
const next = removeKeywordPath(both, 'Nature > Birds');
expect(next.keywords).toEqual(['Robin']);
expect(next.keywordPaths).toEqual(['Nature', 'Garden', 'Garden > Robin']);
});
it('collects suggestions once, sorted', () => {
const rows = [
{ keywordPaths: ['Nature > Birds', 'Nature'] },
{ keywordPaths: ['nature', 'Places > Coast'] },
{},
];
expect(collectKeywordPaths(rows)).toEqual(['Nature', 'Nature > Birds', 'Places > Coast']);
});
it('builds a tree with parents before children', () => {
const tree = keywordTree(['Nature > Birds > Robin', 'Nature > Plants', 'Places']);
expect(tree.map((node) => node.name)).toEqual(['Nature', 'Places']);
const nature = tree[0];
expect(nature.path).toBe('Nature');
expect(nature.children.map((node) => node.name)).toEqual(['Birds', 'Plants']);
expect(nature.children[0].children.map((node) => node.name)).toEqual(['Robin']);
expect(nature.children[0].children[0].path).toBe('Nature > Birds > Robin');
});
it('expands a node to everything under it', () => {
const paths = ['Nature', 'Nature > Birds', 'Nature > Birds > Robin', 'Places > Coast'];
expect(pathsUnder(paths, 'Nature > Birds')).toEqual([
'Nature > Birds',
'Nature > Birds > Robin',
]);
expect(pathsUnder(paths, 'Places')).toEqual(['Places > Coast']);
// A prefix that is not a path boundary must not match.
expect(pathsUnder(paths, 'Nat')).toEqual([]);
});
});
+181
View File
@@ -0,0 +1,181 @@
/**
* Hierarchical keywords, stored so other software can still read them.
*
* A flat keyword list is portable but useless past a few hundred terms; a tree
* is useful but has no agreed storage format. Lightroom's answer is to write
* both: `dc:subject` carries the leaf terms, `lr:hierarchicalSubject` carries
* the full paths. This module keeps the same pair in the catalog:
*
* keywords ['Robin'] <- what search and filters use
* keywordPaths ['Nature > Birds > Robin'] <- where it sits
*
* Ancestors are included in `keywordPaths` the way Lightroom does, so a path is
* never a dangling leaf and importing a sidecar cannot invent a parent.
*
* The separator is `>` with spaces because that is the convention every DAM
* reads and writes; a user typing `Nature>Birds` gets normalised.
*/
export const KEYWORD_SEPARATOR = ' > ';
const MAX_DEPTH = 6;
const MAX_SEGMENT = 48;
export interface KeywordPaths {
keywords: string[];
keywordPaths: string[];
}
/** Split a typed path into clean segments. Accepts `>`, `/` and `|`. */
export function pathSegments(input: string): string[] {
return input
.split(/\s*(?:>|\/|\|)\s*/)
.map((part) => part.trim())
.filter(Boolean)
.slice(0, MAX_DEPTH)
.map((part) => part.slice(0, MAX_SEGMENT));
}
/** Canonical `A > B > C` form for a typed or imported path. */
export function normalizeKeywordPath(input: string): string {
return pathSegments(input).join(KEYWORD_SEPARATOR);
}
/** The leaf term of a path, which is what `keywords` stores. */
export function pathLeaf(path: string): string {
const segments = pathSegments(path);
return segments[segments.length - 1] ?? '';
}
/** `A > B > C` → `['A', 'A > B', 'A > B > C']`. */
export function pathAncestors(path: string): string[] {
const segments = pathSegments(path);
return segments.map((_, index) => segments.slice(0, index + 1).join(KEYWORD_SEPARATOR));
}
function sameKey(a: string, b: string) {
return a.toLowerCase() === b.toLowerCase();
}
function addUnique(list: string[], value: string) {
if (!value) return;
if (list.some((item) => sameKey(item, value))) return;
list.push(value);
}
/**
* Add a typed path (or a plain keyword) to a photo's pair of lists.
*
* A plain word stays flat; anything with a separator also records its
* ancestors. The leaf always lands in `keywords`, so a photo tagged
* `Nature > Birds > Robin` still matches a search for "Robin".
*/
export function addKeywordPath(
current: KeywordPaths,
input: string,
asPath = input.includes('>') || input.includes('/') || input.includes('|'),
): KeywordPaths {
const keywords = [...current.keywords];
const keywordPaths = [...current.keywordPaths];
const normalized = normalizeKeywordPath(input);
if (!normalized) return { keywords, keywordPaths };
addUnique(keywords, pathLeaf(normalized));
if (asPath) {
for (const ancestor of pathAncestors(normalized)) addUnique(keywordPaths, ancestor);
}
return { keywords, keywordPaths };
}
/**
* Remove a path and everything under it, then drop leaves that nothing refers
* to any more. Removing `Birds` must not leave `Robin` behind as a keyword with
* no tree above it, which is how hierarchies rot.
*/
export function removeKeywordPath(current: KeywordPaths, path: string): KeywordPaths {
const target = normalizeKeywordPath(path);
if (!target) return current;
const removed = current.keywordPaths.filter(
(entry) => entry === target || entry.startsWith(`${target}${KEYWORD_SEPARATOR}`),
);
const keywordPaths = current.keywordPaths.filter((entry) => !removed.includes(entry));
// Every leaf the removal takes with it: the node's own and its descendants'.
const goneLeaves = new Set(removed.map((entry) => pathLeaf(entry).toLowerCase()));
goneLeaves.add(pathLeaf(target).toLowerCase());
const stillUsed = new Set(keywordPaths.map((entry) => pathLeaf(entry).toLowerCase()));
const keywords = current.keywords.filter(
(word) => stillUsed.has(word.toLowerCase()) || !goneLeaves.has(word.toLowerCase()),
);
return { keywords, keywordPaths };
}
/** Every path in a library, sorted, for suggestions. */
export function collectKeywordPaths(rows: { keywordPaths?: string[] }[]): string[] {
// Case-insensitive dedupe, first spelling wins: "nature" and "Nature" are
// one suggestion, not two entries that look like a bug.
const seen = new Map<string, string>();
for (const row of rows) {
for (const path of row.keywordPaths ?? []) {
const normalized = normalizeKeywordPath(path);
const key = normalized.toLowerCase();
if (normalized && !seen.has(key)) seen.set(key, normalized);
}
}
return [...seen.values()].sort((a, b) => a.localeCompare(b));
}
export interface KeywordNode {
/** Segment name, e.g. "Birds". */
name: string;
/** Full path, e.g. "Nature > Birds". */
path: string;
children: KeywordNode[];
}
function insert(nodes: KeywordNode[], segments: string[], prefix: string[] = []) {
const [head, ...rest] = segments;
if (!head) return;
// The path is this node's own, built from the prefix above it -- not the
// whole path being inserted, which would rename every parent to its deepest
// descendant.
const selfPath = [...prefix, head];
let node = nodes.find((entry) => entry.name.toLowerCase() === head.toLowerCase());
if (!node) {
node = { name: head, path: selfPath.join(KEYWORD_SEPARATOR), children: [] };
nodes.push(node);
}
if (rest.length > 0) insert(node.children, rest, selfPath);
}
/** Paths → a tree for rendering. Sorted, with parents before children. */
export function keywordTree(paths: string[]): KeywordNode[] {
const roots: KeywordNode[] = [];
for (const path of paths) {
const segments = pathSegments(path);
if (segments.length === 0) continue;
if (segments.length === 1) {
// A flat keyword appears as its own root, with no children.
if (!roots.some((node) => node.name.toLowerCase() === segments[0].toLowerCase())) {
roots.push({ name: segments[0], path: segments[0], children: [] });
}
continue;
}
insert(roots, segments);
}
const sort = (nodes: KeywordNode[]) => {
nodes.sort((a, b) => a.name.localeCompare(b.name));
for (const node of nodes) sort(node.children);
};
sort(roots);
return roots;
}
/** Every path at or under `root`, so tagging a parent tags its children. */
export function pathsUnder(paths: string[], root: string): string[] {
const target = normalizeKeywordPath(root);
if (!target) return [];
return paths.filter(
(path) => path === target || path.startsWith(`${target}${KEYWORD_SEPARATOR}`),
);
}
+77 -2
View File
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { applyFilmVariant, FILM_PRESETS, PRESETS, PRESET_CATEGORIES } from './presets'; import {
import { normalizeEdits } from './edits'; applyFilmVariant,
applyPresetEdits,
FILM_PRESETS,
PRESETS,
PRESET_CATEGORIES,
} from './presets';
import { defaultEdits, normalizeEdits } from './edits';
describe('preset library', () => { describe('preset library', () => {
it('ships an extensive, uniquely identified catalogue', () => { it('ships an extensive, uniquely identified catalogue', () => {
@@ -44,6 +50,21 @@ describe('preset library', () => {
expect(redscale.some((preset) => preset.film?.process === 'E-6')).toBe(true); expect(redscale.some((preset) => preset.film?.process === 'E-6')).toBe(true);
}); });
it('keeps a user preset a full recipe rather than a cast', () => {
const base = { ...defaultEdits(), temp: -24, tint: 9 };
const custom = {
id: 'my-look',
name: 'My look',
group: 'User presets',
custom: true,
edits: { temp: 30, contrast: 12 },
};
const next = applyPresetEdits(base, custom);
expect(next.temp).toBe(30);
expect(next.presetLook).toEqual({ temp: 0, tint: 0 });
expect(next.contrast).toBe(12);
});
it('derives push/pull variants for film stocks only', () => { it('derives push/pull variants for film stocks only', () => {
const stock = FILM_PRESETS[0]; const stock = FILM_PRESETS[0];
expect(applyFilmVariant(stock, 'push').id).toBe(`${stock.id}::push`); expect(applyFilmVariant(stock, 'push').id).toBe(`${stock.id}::push`);
@@ -52,3 +73,57 @@ describe('preset library', () => {
expect(applyFilmVariant(look!, 'push')).toBe(look); expect(applyFilmVariant(look!, 'push')).toBe(look);
}); });
}); });
describe('looks over the photo’s own grade', () => {
const graded = () => ({ ...defaultEdits(), temp: -24, tint: 9 });
it('keeps the white balance already set and layers the look’s cast on it', () => {
const stock = FILM_PRESETS.find((preset) => (preset.edits.temp ?? 0) !== 0)!;
const next = applyPresetEdits(graded(), stock);
expect(next.temp).toBe(-24);
expect(next.tint).toBe(9);
expect(next.presetLook).toEqual({
temp: stock.edits.temp ?? 0,
tint: stock.edits.tint ?? 0,
});
// The look still sets its own tone and colour.
expect(next.contrast).toBe(stock.edits.contrast);
});
it('replaces the previous look’s cast instead of stacking it', () => {
const warm = FILM_PRESETS.find((preset) => (preset.edits.temp ?? 0) > 10)!;
const cool = FILM_PRESETS.find((preset) => (preset.edits.temp ?? 0) < -10)!;
const once = applyPresetEdits(graded(), warm);
const twice = applyPresetEdits(once, cool);
expect(twice.temp).toBe(-24);
expect(twice.tint).toBe(9);
expect(twice.presetLook).toEqual({ temp: cool.edits.temp ?? 0, tint: cool.edits.tint ?? 0 });
});
it('leaves the white balance alone for a preset with no cast of its own', () => {
const plain = PRESETS.find(
(preset) =>
preset.id !== 'original' &&
!preset.film &&
preset.edits.temp === undefined &&
preset.edits.tint === undefined,
)!;
const next = applyPresetEdits(graded(), plain);
expect(next.temp).toBe(-24);
expect(next.tint).toBe(9);
expect(next.presetLook).toEqual({ temp: 0, tint: 0 });
});
it('clears the grade and the cast with the original', () => {
const applied = applyPresetEdits(graded(), FILM_PRESETS[0]);
const original = applyPresetEdits(applied, {
id: 'original',
name: 'Original',
group: 'Essentials',
edits: {},
});
expect(original.temp).toBe(0);
expect(original.tint).toBe(0);
expect(original.presetLook).toEqual({ temp: 0, tint: 0 });
});
});
+39
View File
@@ -1,4 +1,5 @@
import type { BwFilter, Edits, Preset } from '../types'; import type { BwFilter, Edits, Preset } from '../types';
import { defaultEdits, normalizeEdits } from './edits';
const identity = () => [ const identity = () => [
{ x: 0, y: 0 }, { x: 0, y: 0 },
@@ -2925,6 +2926,44 @@ export const PRESETS: Preset[] = ([
: preset; : preset;
}); });
/**
* Applies a look over the grade the photo already has.
*
* White balance is the base the look is graded against: the look's own Temp and
* Tint become a cast in `presetLook` on top of the correction already made,
* instead of overwriting it. Storing the cast apart also means switching looks
* replaces it rather than stacking one stock's warmth on the last one's, and
* the preview tiles can show exactly what the click will produce. A user preset
* is a recipe copied from a photo, so it still replaces the whole grade, and
* "original" clears it.
*/
export function applyPresetEdits(base: Edits, preset: Preset): Edits {
if (preset.id === 'original') {
return { ...defaultEdits(), crop: base.crop, cameraProfile: base.cameraProfile };
}
const { temp = 0, tint = 0, ...look } = preset.edits;
const next: Edits = {
...base,
...look,
crop: base.crop,
// The camera profile belongs to the body that produced the raw.
cameraProfile: base.cameraProfile,
// A strong film response must not leak into the next look.
redscale: look.redscale ?? 0,
};
if (preset.custom) {
// A recipe keeps the white balance it was saved with.
next.temp = temp;
next.tint = tint;
} else {
next.temp = base.temp;
next.tint = base.tint;
next.kelvin = base.kelvin;
next.presetLook = { temp, tint };
}
return normalizeEdits(next);
}
/* ------------------------------------------------------------- film variants */ /* ------------------------------------------------------------- film variants */
export type FilmVariant = 'base' | 'push' | 'pull' | 'warm' | 'cool'; export type FilmVariant = 'base' | 'push' | 'pull' | 'warm' | 'cool';
+66 -1
View File
@@ -1,5 +1,48 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { kelvinGains, wbGainFor, WB_REFERENCE_KELVIN } from './whiteBalance'; import {
estimateKelvin,
expressWhiteBalance,
kelvinGains,
wbGainFor,
wbGainWithLook,
WB_REFERENCE_KELVIN,
} from './whiteBalance';
describe('expressWhiteBalance', () => {
it('recovers the sliders that produced a correction', () => {
for (const [temp, tint] of [
[30, -12],
[-55, 40],
[0, 0],
[80, 60],
]) {
const back = expressWhiteBalance(wbGainFor(temp, tint, null));
expect(back.temp).toBeCloseTo(temp, 0);
expect(back.tint).toBeCloseTo(tint, 0);
}
});
it('reads a look cast as the balance it leaves behind', () => {
const look = { temp: 35, tint: -8 };
const gain = wbGainWithLook(-20, 10, null, look);
const back = expressWhiteBalance(gain);
// The recovered pair reproduces the same gain the look left on the photo, to
// within what whole-number sliders can express.
const again = wbGainFor(back.temp, back.tint, null);
expect(again[0]).toBeCloseTo(gain[0], 2);
expect(again[1]).toBeCloseTo(gain[1], 2);
expect(again[2]).toBeCloseTo(gain[2], 2);
// Warm cast over a cool correction lands near the sum of the two.
expect(back.temp).toBeGreaterThan(11);
expect(back.temp).toBeLessThan(19);
});
it('estimates the Kelvin of an absolute balance', () => {
expect(estimateKelvin(kelvinGains(3200))).toBeGreaterThan(3100);
expect(estimateKelvin(kelvinGains(3200))).toBeLessThan(3300);
expect(estimateKelvin(kelvinGains(WB_REFERENCE_KELVIN))).toBeCloseTo(WB_REFERENCE_KELVIN, -2);
});
});
describe('absolute white balance', () => { describe('absolute white balance', () => {
it('is neutral at the daylight reference', () => { it('is neutral at the daylight reference', () => {
@@ -32,4 +75,26 @@ describe('absolute white balance', () => {
expect(luma).toBeCloseTo(1, 4); expect(luma).toBeCloseTo(1, 4);
} }
}); });
it('grades a look’s cast over the correction already made', () => {
const corrected = wbGainFor(-30, 0, null);
const withLook = wbGainWithLook(-30, 0, null, { temp: 20, tint: 0 });
// The look warms the corrected frame without throwing the correction away.
expect(withLook[0]).toBeGreaterThan(corrected[0]);
expect(withLook[2]).toBeLessThan(corrected[2]);
// Adding the two offsets is what the sliders would do by hand.
const summed = wbGainFor(-10, 0, null);
expect(withLook[0]).toBeCloseTo(summed[0], 2);
expect(withLook[2]).toBeCloseTo(summed[2], 2);
const luma = 0.2126 * withLook[0] + 0.7152 * withLook[1] + 0.0722 * withLook[2];
expect(luma).toBeCloseTo(1, 4);
});
it('leaves the gain untouched when the look has no cast', () => {
expect(wbGainWithLook(0, 0, null, { temp: 0, tint: 0 })).toEqual(wbGainFor(0, 0, null));
// An absolute Kelvin correction is still the base for the cast.
const kelvin = wbGainFor(0, 0, 3200);
const warmed = wbGainWithLook(0, 0, 3200, { temp: 12, tint: 0 });
expect(warmed[0]).toBeGreaterThan(kelvin[0]);
});
}); });
+68
View File
@@ -108,6 +108,74 @@ export function wbGainFor(
return gain.map((v) => v / norm) as [number, number, number]; return gain.map((v) => v / norm) as [number, number, number];
} }
/**
* The white balance with an applied look's cast layered over it.
*
* The correction the photographer already made stays the base: a look's
* Temp/Tint is a cast added on top, not a replacement for it. Keeping the two
* separate (see `Edits['presetLook']`) also lets switching looks swap the cast
* instead of stacking one stock's warmth on the last one's. Normalised again
* so the look changes colour, not exposure.
*/
export function wbGainWithLook(
temp: number,
tint: number,
kelvin: number | null,
look: { temp: number; tint: number } | null | undefined,
): [number, number, number] {
const base = wbGainFor(temp, tint, kelvin);
if (!look || (!look.temp && !look.tint)) return base;
const cast = wbGainFor(look.temp, look.tint, null);
const gain: [number, number, number] = [base[0] * cast[0], base[1] * cast[1], base[2] * cast[2]];
const luma = 0.2126 * gain[0] + 0.7152 * gain[1] + 0.0722 * gain[2];
const norm = Math.max(0.05, luma);
return gain.map((v) => v / norm) as [number, number, number];
}
/**
* The Temp/Tint pair that reproduces a gain vector.
*
* A look layers its cast over the correction, so the two sliders no longer show
* what the photo is graded at. Inverting the gains (ratios only, so the shared
* luma normalisation drops out) gives the pair that would: `r/b` is fixed by
* temperature alone, then green carries the tint.
*/
export function expressWhiteBalance(
gain: readonly number[],
): { temp: number; tint: number } {
const [r, g, b] = gain;
if (![r, g, b].every((v) => Number.isFinite(v) && v > 0)) return { temp: 0, tint: 0 };
// r/b = (1 + 0.3t) / (1 − 0.26t)
const t = (r - b) / (T_R * b + T_B * r);
// g/r = (1 − 0.16i) / ((1 + 0.3t)(1 + 0.06i))
const d = 1 + T_R * t;
const a = g / r;
const i = (1 - a * d) / (TINT_CROSS * a * d + T_TINT);
return {
temp: Math.round(clampRange(t * 100, -100, 100)),
tint: Math.round(clampRange(i * 100, -100, 100)),
};
}
/**
* The Kelvin setting whose black-body balance best matches a gain vector's red
* to blue ratio. Used to report a look's cast on the absolute-Kelvin control.
*/
export function estimateKelvin(gain: readonly number[]): number {
const target = Math.log(Math.max(1e-4, gain[0]) / Math.max(1e-4, gain[2]));
let best = WB_REFERENCE_KELVIN;
let bestErr = Infinity;
for (let k = 1500; k <= 12000; k += 25) {
const [r, , b] = kelvinGains(k);
const err = Math.abs(Math.log(r / b) - target);
if (err < bestErr) {
bestErr = err;
best = k;
}
}
return best;
}
/** /**
* Temperature and tint that make a sampled source colour neutral. * Temperature and tint that make a sampled source colour neutral.
* `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel. * `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel.
+76 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { defaultEdits, defaultLocalLayer, normalizeEdits } from './edits'; import { defaultEdits, defaultLocalLayer, normalizeEdits } from './edits';
import { editsToXmp, xmpFileName, xmpToEdits } from './xmp'; import { editsToXmp, xmpFileName, xmpToEdits, xmpToMetadata } from './xmp';
describe('xmp sidecars', () => { describe('xmp sidecars', () => {
it('round-trips every develop field exactly', () => { it('round-trips every develop field exactly', () => {
@@ -55,3 +55,78 @@ describe('xmp sidecars', () => {
expect(xmpFileName('no-extension')).toBe('no-extension.xmp'); expect(xmpFileName('no-extension')).toBe('no-extension.xmp');
}); });
}); });
describe('xmp metadata', () => {
const photo = {
name: 'DSC0123.ARW',
meta: {},
rating: 4,
color: 'green' as const,
keywords: ['Birds', 'Robin'],
keywordPaths: ['Nature', 'Nature > Birds', 'Nature > Birds > Robin'],
iptc: {
headline: 'Dawn chorus',
credit: 'B. Hursey',
source: 'Field notes',
city: 'Bristol',
state: 'Somerset',
country: 'UK',
location: 'Ashton Court',
},
title: 'Robin at dawn',
caption: 'First light, heavy frost',
creator: 'Brian Hursey',
copyright: '© 2026 Brian Hursey',
};
it('writes rating, label, keywords, hierarchy and IPTC, and reads them back', () => {
const xml = editsToXmp(defaultEdits(), photo);
expect(xml).toContain('xmp:Rating="4"');
expect(xml).toContain('xmp:Label="Green"');
expect(xml).toContain('<lr:hierarchicalSubject>');
expect(xml).toContain('photoshop:City="Bristol"');
expect(xml).toContain('Iptc4xmpCore:Location="Ashton Court"');
const meta = xmpToMetadata(xml);
expect(meta.rating).toBe(4);
expect(meta.label).toBe('green');
expect(meta.keywords).toEqual(['Birds', 'Robin']);
expect(meta.keywordPaths).toEqual([
'Nature',
'Nature > Birds',
'Nature > Birds > Robin',
]);
expect(meta.iptc).toEqual(photo.iptc);
expect(meta.title).toBe('Robin at dawn');
expect(meta.caption).toBe('First light, heavy frost');
expect(meta.creator).toBe('Brian Hursey');
expect(meta.copyright).toBe('© 2026 Brian Hursey');
});
it('reads a sidecar written by Lightroom', () => {
const xml = `<?xpacket begin=""?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:lr="http://ns.adobe.com/lightroom/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmp:Rating="2" xmp:Label="Red" photoshop:Headline="Press day" photoshop:Country="Ireland"><dc:subject><rdf:Bag><rdf:li>Portrait</rdf:li><rdf:li>Maya</rdf:li></rdf:Bag></dc:subject><lr:hierarchicalSubject><rdf:Bag><rdf:li>People &gt; Portrait</rdf:li></rdf:Bag></lr:hierarchicalSubject></rdf:Description></rdf:RDF></x:xmpmeta>`;
const meta = xmpToMetadata(xml);
expect(meta.rating).toBe(2);
expect(meta.label).toBe('red');
expect(meta.keywords).toEqual(['Portrait', 'Maya']);
expect(meta.keywordPaths).toEqual(['People > Portrait']);
expect(meta.iptc.headline).toBe('Press day');
expect(meta.iptc.country).toBe('Ireland');
// Nothing the file does not carry is invented.
expect(meta.iptc.city).toBeUndefined();
expect(meta.caption).toBeUndefined();
});
it('stays quiet when the file has no metadata', () => {
const meta = xmpToMetadata(editsToXmp(defaultEdits()));
expect(meta.rating).toBeUndefined();
expect(meta.label).toBeUndefined();
expect(meta.keywords).toEqual([]);
expect(meta.keywordPaths).toEqual([]);
expect(meta.iptc).toEqual({});
});
it('rejects a file that is not a sidecar', () => {
expect(() => xmpToMetadata('<html></html>')).toThrow(/not an XMP/);
});
});
+184 -6
View File
@@ -1,6 +1,60 @@
import type { Edits, PhotoRecord } from '../types'; import type { ColorLabel, Edits, IptcFields, PhotoRecord } from '../types';
import { normalizeEdits } from './edits'; import { normalizeEdits } from './edits';
/**
* Everything a sidecar carries besides the develop settings: rating, label,
* keywords (flat and hierarchical) and the IPTC core.
*
* `dc:subject` and `lr:hierarchicalSubject` are written as a pair, the way
* Lightroom does: the leaves in the first, the full paths in the second. A
* reader that only understands one of them still gets something usable, and a
* library round-tripped through another editor keeps its tree.
*/
export type XmpPhotoFields = Partial<
Pick<
PhotoRecord,
| 'name'
| 'meta'
| 'rating'
| 'color'
| 'keywords'
| 'keywordPaths'
| 'iptc'
| 'title'
| 'caption'
| 'creator'
| 'copyright'
>
>;
/** Lightroom's label names, which are what other software reads. */
const LABEL_NAMES: Record<Exclude<ColorLabel, ''>, string> = {
red: 'Red',
yellow: 'Yellow',
green: 'Green',
blue: 'Blue',
purple: 'Purple',
};
const LABEL_VALUES: Record<string, Exclude<ColorLabel, ''>> = {
red: 'red',
yellow: 'yellow',
green: 'green',
blue: 'blue',
purple: 'purple',
};
/** IPTC field → the XMP property that carries it. */
const IPTC_ATTRS: [keyof IptcFields, string][] = [
['headline', 'photoshop:Headline'],
['credit', 'photoshop:Credit'],
['source', 'photoshop:Source'],
['city', 'photoshop:City'],
['state', 'photoshop:State'],
['country', 'photoshop:Country'],
['location', 'Iptc4xmpCore:Location'],
];
/** /**
* Lightroom-compatible XMP sidecars. * Lightroom-compatible XMP sidecars.
* *
@@ -105,7 +159,70 @@ export function xmpFileName(name: string) {
return `${name.replace(/\.[^.]+$/, '') || 'photo'}.xmp`; return `${name.replace(/\.[^.]+$/, '') || 'photo'}.xmp`;
} }
export function editsToXmp(edits: Edits, photo?: Pick<PhotoRecord, 'name' | 'meta'>): string { /** Rating, colour label and IPTC, as XMP attributes on the Description. */
export function photoMetadataAttributes(photo?: XmpPhotoFields): string {
if (!photo) return '';
const attrs: string[] = [];
const rating = Math.round(photo.rating ?? 0);
if (rating > 0) attrs.push(`xmp:Rating="${Math.max(0, Math.min(5, rating))}"`);
const label = photo.color ? LABEL_NAMES[photo.color] : '';
if (label) attrs.push(`xmp:Label="${label}"`);
const iptc = photo.iptc ?? {};
for (const [field, property] of IPTC_ATTRS) {
const value = iptc[field];
if (typeof value === 'string' && value.trim()) {
attrs.push(`${property}="${escapeXml(value.trim())}"`);
}
}
return attrs.length ? ` ${attrs.join(' ')}` : '';
}
/** Title, caption, creator, rights, keywords and the hierarchy, as elements. */
export function photoMetadataElements(photo?: XmpPhotoFields): string {
const parts: string[] = [];
const title = photo?.title?.trim() || photo?.name?.trim() || 'Luminary edit';
parts.push(
`<dc:title><rdf:Alt><rdf:li xml:lang="x-default">${escapeXml(title)}</rdf:li></rdf:Alt></dc:title>`,
);
if (photo?.caption?.trim()) {
parts.push(
`<dc:description><rdf:Alt><rdf:li xml:lang="x-default">${escapeXml(
photo.caption.trim(),
)}</rdf:li></rdf:Alt></dc:description>`,
);
}
if (photo?.creator?.trim()) {
parts.push(
`<dc:creator><rdf:Seq><rdf:li>${escapeXml(photo.creator.trim())}</rdf:li></rdf:Seq></dc:creator>`,
);
}
if (photo?.copyright?.trim()) {
parts.push(
`<dc:rights><rdf:Alt><rdf:li xml:lang="x-default">${escapeXml(
photo.copyright.trim(),
)}</rdf:li></rdf:Alt></dc:rights>`,
);
}
const keywords = (photo?.keywords ?? []).filter((word) => word && word.trim());
if (keywords.length) {
parts.push(
`<dc:subject><rdf:Bag>${keywords
.map((word) => `<rdf:li>${escapeXml(word)}</rdf:li>`)
.join('')}</rdf:Bag></dc:subject>`,
);
}
const paths = (photo?.keywordPaths ?? []).filter((path) => path && path.trim());
if (paths.length) {
parts.push(
`<lr:hierarchicalSubject><rdf:Bag>${paths
.map((path) => `<rdf:li>${escapeXml(path)}</rdf:li>`)
.join('')}</rdf:Bag></lr:hierarchicalSubject>`,
);
}
return parts.join('');
}
export function editsToXmp(edits: Edits, photo?: XmpPhotoFields): string {
const normalized = normalizeEdits(edits); const normalized = normalizeEdits(edits);
const attrs = CRS_FIELDS.map( const attrs = CRS_FIELDS.map(
([name, read]) => `crs:${name}="${num(read(normalized))}"`, ([name, read]) => `crs:${name}="${num(read(normalized))}"`,
@@ -113,16 +230,15 @@ export function editsToXmp(edits: Edits, photo?: Pick<PhotoRecord, 'name' | 'met
attrs.push(`crs:ConvertToGrayscale="${normalized.bw ? 'True' : 'False'}"`); attrs.push(`crs:ConvertToGrayscale="${normalized.bw ? 'True' : 'False'}"`);
if (normalized.kelvin != null) attrs.push(`crs:Temperature="${Math.round(normalized.kelvin)}"`); if (normalized.kelvin != null) attrs.push(`crs:Temperature="${Math.round(normalized.kelvin)}"`);
attrs.push(`lum:Settings="${escapeXml(base64Encode(JSON.stringify(normalized)))}"`); attrs.push(`lum:Settings="${escapeXml(base64Encode(JSON.stringify(normalized)))}"`);
const label = photo ? escapeXml(photo.name) : 'Luminary edit';
return [ return [
'<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>', '<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>',
'<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Luminary">', '<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Luminary">',
' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">', ' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">',
` <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmlns:lum="${LUM_NS}"`, ` <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmlns:lum="${LUM_NS}" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:Iptc4xmpCore="http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:lr="http://ns.adobe.com/lightroom/1.0/"`,
' crs:Version="15.0" crs:ProcessVersion="15.4" crs:HasSettings="True"', ' crs:Version="15.0" crs:ProcessVersion="15.4" crs:HasSettings="True"',
` ${attrs.join('\n ')}>`, ` ${attrs.join('\n ')}${photoMetadataAttributes(photo)}>`,
` <dc:title xmlns:dc="http://purl.org/dc/elements/1.1/"><rdf:Alt><rdf:li xml:lang="x-default">${label}</rdf:li></rdf:Alt></dc:title>`, ` ${photoMetadataElements(photo)}`,
' </rdf:Description>', ' </rdf:Description>',
' </rdf:RDF>', ' </rdf:RDF>',
'</x:xmpmeta>', '</x:xmpmeta>',
@@ -202,6 +318,68 @@ export function xmpToEdits(xml: string, base: Edits): XmpImport {
return { edits: normalizeEdits(next), source: 'lightroom', applied }; return { edits: normalizeEdits(next), source: 'lightroom', applied };
} }
export interface XmpMetadata {
rating?: number;
label?: Exclude<ColorLabel, ''>;
keywords: string[];
keywordPaths: string[];
iptc: IptcFields;
title?: string;
caption?: string;
creator?: string;
copyright?: string;
}
/** `<dc:subject><rdf:Bag><rdf:li>…` → the items, unescaped. */
function bagItems(xml: string, tag: string): string[] {
const block = new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*?)</${tag}>`).exec(xml);
if (!block) return [];
return [...block[1].matchAll(/<rdf:li\b[^>]*>([\s\S]*?)<\/rdf:li>/g)]
.map((match) => unescapeXml(match[1].trim()))
.filter(Boolean);
}
/**
* Read the metadata half of a sidecar: rating, label, keywords, hierarchy and
* IPTC. Separate from `xmpToEdits` because a photographer may want the
* cataloguing fields from a file whose grade they do not want to adopt.
*
* Returns the fields the file actually carries; the caller decides what to
* overwrite, so an empty sidecar cannot wipe a photo's existing metadata.
*/
export function xmpToMetadata(xml: string): XmpMetadata {
if (!/<x:xmpmeta|<rdf:RDF/i.test(xml)) {
throw new Error('That file is not an XMP sidecar');
}
const attrs = attributes(xml);
const ratingRaw = attrs.get('xmp:Rating');
const ratingValue = ratingRaw === undefined ? NaN : Number(ratingRaw);
const rating = Number.isFinite(ratingValue)
? Math.max(0, Math.min(5, Math.round(ratingValue)))
: undefined;
const label = LABEL_VALUES[(attrs.get('xmp:Label') ?? '').toLowerCase()];
const iptc: IptcFields = {};
for (const [field, property] of IPTC_ATTRS) {
const value = attrs.get(property);
if (value) iptc[field] = value.slice(0, 256);
}
return {
rating,
label,
keywords: bagItems(xml, 'dc:subject'),
keywordPaths: bagItems(xml, 'lr:hierarchicalSubject'),
iptc,
title: bagItems(xml, 'dc:title')[0],
caption: bagItems(xml, 'dc:description')[0],
creator: bagItems(xml, 'dc:creator')[0],
copyright: bagItems(xml, 'dc:rights')[0],
};
}
/** Opens the OS picker and returns the sidecar text, or null when cancelled. */ /** Opens the OS picker and returns the sidecar text, or null when cancelled. */
export function readXmpFile(): Promise<string | null> { export function readXmpFile(): Promise<string | null> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
+19 -9
View File
@@ -1,9 +1,15 @@
import { lazy, Suspense } from 'react';
import { createRoot } from 'react-dom/client'; import { createRoot } from 'react-dom/client';
import App from './App'; import App from './App';
import ProofingGallery from './components/ProofingGallery'; import ErrorBoundary from './components/ErrorBoundary';
import JoinPage from './components/JoinPage';
import './styles.css'; import './styles.css';
// Proofing galleries and invite pages are public and self-contained: loading
// them lazily keeps the editor out of the chunk a client downloads to view a
// shoot, and keeps the invite page tiny.
const ProofingGallery = lazy(() => import('./components/ProofingGallery'));
const JoinPage = lazy(() => import('./components/JoinPage'));
const root = document.getElementById('root'); const root = document.getElementById('root');
if (!root) throw new Error('root element missing'); if (!root) throw new Error('root element missing');
@@ -14,11 +20,15 @@ const galleryMatch = /^\/g\/([A-Za-z0-9_-]+)\/?$/.exec(window.location.pathname)
const joinMatch = /^\/join\/([A-Za-z0-9_-]+)\/?$/.exec(window.location.pathname); const joinMatch = /^\/join\/([A-Za-z0-9_-]+)\/?$/.exec(window.location.pathname);
createRoot(root).render( createRoot(root).render(
galleryMatch ? ( <ErrorBoundary>
<ProofingGallery token={galleryMatch[1]} /> <Suspense fallback={null}>
) : joinMatch ? ( {galleryMatch ? (
<JoinPage token={joinMatch[1]} /> <ProofingGallery token={galleryMatch[1]} />
) : ( ) : joinMatch ? (
<App /> <JoinPage token={joinMatch[1]} />
), ) : (
<App />
)}
</Suspense>
</ErrorBoundary>,
); );
+119 -8
View File
@@ -604,6 +604,21 @@ img {
font-size: 11px; font-size: 11px;
} }
.model-picker {
display: flex;
gap: 3px;
padding: 3px;
margin: 2px 0 6px;
width: fit-content;
background: var(--panel-3);
border-radius: 6px;
}
.model-picker .chip {
border-radius: 3px;
font-size: 11px;
}
.color-filter { .color-filter {
display: flex; display: flex;
gap: 5px; gap: 5px;
@@ -1635,6 +1650,27 @@ figcaption {
margin-top: 2px; margin-top: 2px;
} }
/* The look's cast and the balance it leaves the photo at, under Temp/Tint. */
.wb-look {
display: flex;
flex-wrap: wrap;
gap: 2px 10px;
margin: 1px 0 5px;
font-size: 10.5px;
color: var(--muted);
}
.wb-look b {
color: #d9d9e2;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.wb-look-final {
margin-left: auto;
font-variant-numeric: tabular-nums;
}
.row { .row {
display: grid; display: grid;
grid-template-columns: 74px 1fr 44px; grid-template-columns: 74px 1fr 44px;
@@ -5058,14 +5094,14 @@ figcaption {
border-top: 1px solid var(--line); border-top: 1px solid var(--line);
} }
.lens-split { .compare-split {
position: absolute; position: absolute;
inset: 0; inset: 0;
pointer-events: none; pointer-events: none;
z-index: 3; z-index: 3;
} }
.lens-split-line { .compare-split-line {
position: absolute; position: absolute;
top: 0; top: 0;
bottom: 0; bottom: 0;
@@ -5074,7 +5110,7 @@ figcaption {
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.55), 0 0 10px rgba(0, 0, 0, 0.45); box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.55), 0 0 10px rgba(0, 0, 0, 0.45);
} }
.lens-split-handle { .compare-split-handle {
position: absolute; position: absolute;
top: 50%; top: 50%;
display: flex; display: flex;
@@ -5096,14 +5132,14 @@ figcaption {
touch-action: none; touch-action: none;
} }
.lens-split-handle:hover, .compare-split-handle:hover,
.lens-split-handle:focus-visible { .compare-split-handle:focus-visible {
background: var(--accent); background: var(--accent);
border-color: #fff; border-color: #fff;
outline: none; outline: none;
} }
.lens-split-label { .compare-split-label {
position: absolute; position: absolute;
top: 10px; top: 10px;
padding: 2px 6px; padding: 2px 6px;
@@ -5115,11 +5151,11 @@ figcaption {
text-transform: uppercase; text-transform: uppercase;
} }
.lens-split-label.before { .compare-split-label.before {
left: 10px; left: 10px;
} }
.lens-split-label.after { .compare-split-label.after {
right: 10px; right: 10px;
} }
@@ -6066,3 +6102,78 @@ figcaption {
line-height: 1.7; line-height: 1.7;
font-size: 12px; font-size: 12px;
} }
/* ---------------------------------------------------------- crash boundary */
/* Shown instead of a blank page when rendering throws. Kept light on purpose:
it must not depend on any component that could itself be broken. */
.crash-screen {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
background: var(--bg);
color: var(--text);
}
.crash-card {
width: min(560px, 100%);
padding: 26px 28px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.45);
}
.crash-card h1 {
margin: 0 0 10px;
font-size: 18px;
font-weight: 600;
}
.crash-card p {
margin: 0 0 12px;
color: var(--muted);
line-height: 1.6;
font-size: 13px;
}
.crash-card .crash-message {
padding: 10px 12px;
border-left: 3px solid var(--danger);
background: rgba(224, 93, 93, 0.08);
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
word-break: break-word;
}
.crash-details {
margin-top: 16px;
color: var(--muted);
font-size: 12px;
}
.crash-details summary {
cursor: pointer;
margin-bottom: 8px;
}
.crash-details pre {
max-height: 240px;
overflow: auto;
padding: 10px 12px;
background: var(--bg);
border: 1px solid var(--line);
border-radius: var(--radius);
white-space: pre-wrap;
word-break: break-word;
font-size: 11px;
line-height: 1.5;
}
.crash-card a.btn {
text-decoration: none;
display: inline-flex;
align-items: center;
}
+32 -1
View File
@@ -167,6 +167,13 @@ export interface Edits {
* the demosaiced proxy is assumed to be balanced for. * the demosaiced proxy is assumed to be balanced for.
*/ */
kelvin: number | null; kelvin: number | null;
/**
* White-balance cast of an applied look (film stock or preset), kept apart
* from `temp`/`tint`. A look grades on top of the correction already made,
* so an adjusted white balance stays the base it is applied against instead
* of being replaced by the look's own cast.
*/
presetLook: { temp: number; tint: number };
exposure: number; exposure: number;
/** pulls clipped highlights back into range without shifting hue */ /** pulls clipped highlights back into range without shifting hue */
recovery: number; recovery: number;
@@ -224,7 +231,7 @@ export interface Edits {
* generated asset and is null until one exists; `amount` blends it over the * generated asset and is null until one exists; `amount` blends it over the
* source. Separate from `noise`, which is a small GPU-side filter. * source. Separate from `noise`, which is a small GPU-side filter.
*/ */
aiDenoise: { amount: number; key: string | null; model: string }; aiDenoise: { amount: number; key: string | null; model: 'guided' | 'nlm' | 'scunet' };
/** fringe removal amounts for the two casts lens CA produces */ /** fringe removal amounts for the two casts lens CA produces */
defringe: { purple: number; green: number }; defringe: { purple: number; green: number };
/** spot healing, applied to the source before grading */ /** spot healing, applied to the source before grading */
@@ -241,6 +248,21 @@ export interface Edits {
crop: CropState; crop: CropState;
} }
/** IPTC core fields, written to XMP so a catalog is readable elsewhere. */
export interface IptcFields {
/** Single-line summary, the "who/what" a picture desk reads first. */
headline?: string;
/** Who gets the credit for the image. */
credit?: string;
/** Agency or organisation that supplied it. */
source?: string;
city?: string;
state?: string;
country?: string;
/** Sublocation inside the city. */
location?: string;
}
export interface PhotoMeta { export interface PhotoMeta {
camera?: string; camera?: string;
lens?: string; lens?: string;
@@ -269,6 +291,8 @@ export interface MetadataPreset {
creator?: string; creator?: string;
copyright?: string; copyright?: string;
keywords: string[]; keywords: string[];
keywordPaths?: string[];
iptc?: IptcFields;
} }
export interface SmartCollection { export interface SmartCollection {
@@ -305,6 +329,13 @@ export interface PhotoRecord {
flag: Flag; flag: Flag;
color: ColorLabel; color: ColorLabel;
keywords: string[]; keywords: string[];
/**
* Full hierarchical paths (`A > B > C`). The leaf of each is also in
* `keywords`, so search and filters do not need to know about the tree.
*/
keywordPaths?: string[];
/** IPTC core, edited in the Metadata panel and written to XMP. */
iptc?: IptcFields;
title?: string; title?: string;
caption?: string; caption?: string;
creator?: string; creator?: string;
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+1 -1
View File
@@ -23,7 +23,7 @@ COPY . .
# Build-time dependencies for vite and tsc; the Windows runtime dependencies are # Build-time dependencies for vite and tsc; the Windows runtime dependencies are
# installed separately by build.mjs with --os=win32 --cpu=x64. # installed separately by build.mjs with --os=win32 --cpu=x64.
RUN npm ci --no-audit --no-fund RUN ONNXRUNTIME_NODE_INSTALL=skip npm ci --no-audit --no-fund
# --allow-dirty: the build context has no .git, so the worktree check is skipped. # --allow-dirty: the build context has no .git, so the worktree check is skipped.
# The Go toolchain makes build.mjs produce Luminary.exe instead of the .cmd/.vbs # The Go toolchain makes build.mjs produce Luminary.exe instead of the .cmd/.vbs
+22 -13
View File
@@ -37,8 +37,10 @@ not assumed:
| `node.exe` (v24.22.2) | only Windows system DLLs (`KERNEL32`, `ADVAPI32`, `WS2_32`, `CRYPT32`, `USER32`, …) — statically linked C runtime, so **no Visual C++ Redistributable** | | `node.exe` (v24.22.2) | only Windows system DLLs (`KERNEL32`, `ADVAPI32`, `WS2_32`, `CRYPT32`, `USER32`, …) — statically linked C runtime, so **no Visual C++ Redistributable** |
| `libvips-42.dll` + `sharp` | the Universal C Runtime (`api-ms-win-crt-*`), included in Windows 10/11; older Windows needs KB2999226 | | `libvips-42.dll` + `sharp` | the Universal C Runtime (`api-ms-win-crt-*`), included in Windows 10/11; older Windows needs KB2999226 |
| `libraw.wasm` | a browser with WebAssembly | | `libraw.wasm` | a browser with WebAssembly |
| launcher (`.cmd`/`.vbs`) | Windows PowerShell 5.1, included in Windows 10/11 | | `Luminary.exe` launcher | only Windows system DLLs; no PowerShell, no Windows Script Host |
| Develop module | a current browser with WebGL2 (Edge, Chrome, Firefox) | | launcher (`.cmd`/`.vbs` fallback) | Windows PowerShell 5.1, included in Windows 10/11 |
| `LuminaryWindow.exe` | the Microsoft Edge WebView2 runtime that ships with Windows 10/11 (window engine only; no browser UI, profile or account) |
| Develop module | WebGL2, provided by WebView2 (or by the fallback browser) |
So: a clean Windows 10/11 x64 machine, a browser, and ~250 MB where the data So: a clean Windows 10/11 x64 machine, a browser, and ~250 MB where the data
folder lives. No VC++ redist, no .NET, no admin prompt. The setup exe installs folder lives. No VC++ redist, no .NET, no admin prompt. The setup exe installs
@@ -88,8 +90,8 @@ Output:
``` ```
<out>/ <out>/
Luminary-0.5.1-win-x64.zip the portable deliverable Luminary-0.5.4-win-x64.zip the portable deliverable
installer/Luminary-0.5.1-win-x64-setup.exe the per-user installer installer/Luminary-0.5.4-win-x64-setup.exe the per-user installer
stage/Luminary/ the unpacked bundle (kept for inspection) stage/Luminary/ the unpacked bundle (kept for inspection)
cache/node-v24.22.2-win-x64.exe pinned runtime, reused next time cache/node-v24.22.2-win-x64.exe pinned runtime, reused next time
cache/SHASUMS256-v24.22.2.txt cache/SHASUMS256-v24.22.2.txt
@@ -143,7 +145,7 @@ runs them from there, so no root install is needed. Install it yourself with
<https://nsis.sourceforge.io>. Compile by hand with: <https://nsis.sourceforge.io>. Compile by hand with:
```bash ```bash
makensis -DAPP_VERSION=0.5.1 -DAPP_VERSION4=0.5.1.0 \ makensis -DAPP_VERSION=0.5.4 -DAPP_VERSION4=0.5.4.0 \
-DSOURCE_DIR="$PWD/stage/Luminary" windows/installer.nsi -DSOURCE_DIR="$PWD/stage/Luminary" windows/installer.nsi
``` ```
@@ -158,7 +160,7 @@ running copy works without killing every `node.exe` on the machine.
Silent install and uninstall, for a script or a school lab image: Silent install and uninstall, for a script or a school lab image:
```bat ```bat
Luminary-0.5.1-win-x64-setup.exe /S Luminary-0.5.4-win-x64-setup.exe /S
"%LOCALAPPDATA%\Programs\Luminary\Uninstall.exe" /S "%LOCALAPPDATA%\Programs\Luminary\Uninstall.exe" /S
``` ```
@@ -283,9 +285,9 @@ Full behaviour, edge cases and the test checklist: [launcher/DESIGN.md](launcher
```bash ```bash
cd <out> cd <out>
sha256sum Luminary-0.5.1-win-x64.zip sha256sum Luminary-0.5.4-win-x64.zip
unzip -t Luminary-0.5.1-win-x64.zip | tail -1 unzip -t Luminary-0.5.4-win-x64.zip | tail -1
unzip -l Luminary-0.5.1-win-x64.zip | grep -E 'node.exe|Luminary\.(exe|cmd|vbs)|app/server/index.mjs' unzip -l Luminary-0.5.4-win-x64.zip | grep -E 'node.exe|Luminary\.(exe|cmd|vbs)|app/server/index.mjs'
``` ```
On Windows, the real test is the checklist in `launcher/DESIGN.md` §15, On Windows, the real test is the checklist in `launcher/DESIGN.md` §15,
@@ -342,8 +344,15 @@ then replaces `node.exe`. It refuses while Luminary is running. Set
fall back to a system Node 24+ in the meantime. fall back to a system Node 24+ in the meantime.
- No tray icon and no auto-update in this version (both are launcher features, - No tray icon and no auto-update in this version (both are launcher features,
not app changes). not app changes).
- Loopback only by default; set `HOST=0.0.0.0` for LAN proofing galleries. - Loopback only by default: the local engine is a background service on this
- The PowerShell launcher cannot clean up after a server crash; a stale PC that listens on `127.0.0.1`. Set `HOST=0.0.0.0` only for LAN proofing
galleries.
- Fully offline: the app, the catalog and the start-up wait are local. The
launcher probes `127.0.0.1` over plain TCP, which never consults the system
proxy or DNS, so a disconnected network, VPN or proxy setting cannot stop it
from starting. Only `-Repair` (downloading `node.exe`) and the optional Immich
sync use the network.
- The PowerShell launcher cannot clean up after the local engine crashes; a stale
`runtime.json` is simply ignored on the next start. `runtime.json` is simply ignored on the next start.
- The setup exe cannot be executed on the Linux build host. It is verified by - The setup exe cannot be executed on the Linux build host. It is verified by
unpacking it and comparing the SHA-256 of every payload file with the staged unpacking it and comparing the SHA-256 of every payload file with the staged
@@ -360,11 +369,11 @@ then replaces `node.exe`. It refuses while Luminary is running. Set
| "Luminary needs Windows 10 or 11" (exit 4) | the launcher read `CurrentBuild` below 10240. The app targets Windows 10/11; there is no Windows 7/8 build | | "Luminary needs Windows 10 or 11" (exit 4) | the launcher read `CurrentBuild` below 10240. The app targets Windows 10/11; there is no Windows 7/8 build |
| "The Universal C Runtime is missing" | Windows 8.1 without KB2999226 — install <https://support.microsoft.com/help/2999226> or use Windows 10/11 | | "The Universal C Runtime is missing" | Windows 8.1 without KB2999226 — install <https://support.microsoft.com/help/2999226> or use Windows 10/11 |
| "The data drive has only … GB free" | free space before starting; catalogs and previews grow in `%LOCALAPPDATA%` | | "The data drive has only … GB free" | free space before starting; catalogs and previews grow in `%LOCALAPPDATA%` |
| "did not answer on /api/health" | `logs\server.err.log`; run `node app\server\index.mjs` from `app\` to see the failure | | "did not answer on /api/health" | `logs\server.err.log`; run `node app\server\index.mjs` from `app\` to see the failure. This is not a network error: start-up only talks to `127.0.0.1`, so a disconnected machine starts the same way |
| Browser opens an error page | the port was taken between the check and the spawn; start again | | Browser opens an error page | the port was taken between the check and the spawn; start again |
| RAW import fails | `app\node_modules\@img\sharp-win32-x64` must contain a `.node` binary; RAW decode itself is wasm | | RAW import fails | `app\node_modules\@img\sharp-win32-x64` must contain a `.node` binary; RAW decode itself is wasm |
| `node.exe failed its SHA-256 check` | delete `<out>/cache` and rebuild (the download was truncated) | | `node.exe failed its SHA-256 check` | delete `<out>/cache` and rebuild (the download was truncated) |
| A sign-in screen appears | the server was started without `LUMINARY_LOCAL=1`, or it is the normal server, not the bundle | | A sign-in screen appears | the local engine was started without `LUMINARY_LOCAL=1`, or this is the full multi-user edition, not the desktop bundle |
| Opens as a normal tab | Edge/Chrome not found, or `-Browser` / `LUMINARY_WINDOW=browser` was used | | Opens as a normal tab | Edge/Chrome not found, or `-Browser` / `LUMINARY_WINDOW=browser` was used |
| Build refuses `--out` | the path is inside the repo; choose one outside | | Build refuses `--out` | the path is inside the repo; choose one outside |
| SmartScreen on first run | unsigned build: "More info" → "Run anyway" (same for the setup exe) | | SmartScreen on first run | unsigned build: "More info" → "Run anyway" (same for the setup exe) |
+2 -2
View File
@@ -40,9 +40,9 @@ second implementation to drift.
``` ```
repo=https://git.maple-street.net/bhursey/luminary.git repo=https://git.maple-street.net/bhursey/luminary.git
tag=v0.5.1 tag=v0.5.4
commit=fb43ca8f1c2d… # full sha commit=fb43ca8f1c2d… # full sha
version=0.5.1 # package.json version, checked after fetch version=0.5.4 # package.json version, checked after fetch
node=v24.22.2 node=v24.22.2
``` ```
+64
View File
@@ -144,6 +144,70 @@ try {
Check '/api/sync answers' $false $_.Exception.Message Check '/api/sync answers' $false $_.Exception.Message
} }
Say ''
Say 'Offline import (proxy unreachable)'
# The failure this guards against: with the network down, anything that asks
# Windows for its proxy/PAC cannot reach 127.0.0.1, so the launcher gave up on
# a healthy engine and the app window reported that it could not reach it.
$launcherText = Get-Content -LiteralPath $launcher -Raw
Check 'health probe uses a direct socket' ($launcherText -match 'TcpClient')
Check 'health probe avoids the proxy stack' ($launcherText -notmatch 'Invoke-WebRequest')
Check 'app window bypasses proxies' ($launcherText -match '--no-proxy-server')
# The import the page performs, run with every proxy variable pointing at a
# black hole: upload, decode in the bundle, read the preview back.
$probe = Join-Path $dataDir 'offline-import.cjs'
Set-Content -LiteralPath $probe -Encoding ASCII -Value @'
const fs = require('node:fs');
const path = require('node:path');
const [bundle, base, dir] = process.argv.slice(2);
const sharp = require(path.join(bundle, 'app', 'node_modules', 'sharp'));
(async () => {
const file = path.join(dir, 'offline-smoke.tiff');
await sharp({ create: { width: 8, height: 8, channels: 3, background: { r: 200, g: 100, b: 50 } } })
.tiff()
.toFile(file);
const health = await fetch(base + '/api/health');
const upload = await fetch(
base + '/api/photos/smoke-offline/original?name=offline-smoke.tiff&mime=image%2Ftiff',
{ method: 'POST', headers: { 'Content-Type': 'image/tiff' }, body: fs.readFileSync(file) },
);
const body = await upload.json().catch(() => ({}));
let preview = 0;
if (body.previewUrl) {
const target = String(body.previewUrl).startsWith('http') ? body.previewUrl : base + body.previewUrl;
preview = (await fetch(target)).status;
}
process.stdout.write(JSON.stringify({ health: health.status, upload: upload.status, preview }));
})().catch((error) => {
process.stdout.write(JSON.stringify({ error: String(error) }));
process.exit(1);
});
'@
$proxyNames = @('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy')
$noProxyNames = @('NO_PROXY', 'no_proxy')
$saved = @{}
foreach ($name in $proxyNames + $noProxyNames) {
$saved[$name] = [Environment]::GetEnvironmentVariable($name, 'Process')
}
try {
foreach ($name in $proxyNames) { Set-Item -Path "env:$name" -Value 'http://10.255.255.1:9' }
foreach ($name in $noProxyNames) { Remove-Item -Path "env:$name" -ErrorAction SilentlyContinue }
$offline = (& $nodeExe $probe $Bundle $url $dataDir | Out-String).Trim()
} finally {
foreach ($name in $proxyNames + $noProxyNames) {
if ($saved[$name]) { Set-Item -Path "env:$name" -Value $saved[$name] }
else { Remove-Item -Path "env:$name" -ErrorAction SilentlyContinue }
}
}
$offlineResult = $null
try { $offlineResult = $offline | ConvertFrom-Json } catch { }
Check 'engine answers with the proxy unreachable' ($null -ne $offlineResult -and $offlineResult.health -eq 200) $(if ($offlineResult) { "health $($offlineResult.health)" } else { $offline })
# A new upload is created (201); replacing one answers 200.
Check 'import upload accepted offline' ($null -ne $offlineResult -and $offlineResult.upload -in @(200, 201)) $(if ($offlineResult) { "upload $($offlineResult.upload)" } else { '' })
Check 'preview decodes offline' ($null -ne $offlineResult -and $offlineResult.preview -eq 200) $(if ($offlineResult) { "preview $($offlineResult.preview)" } else { '' })
Say '' Say ''
Say 'Window (WebView2)' Say 'Window (WebView2)'
if (-not (Test-Path -LiteralPath $windowExe)) { if (-not (Test-Path -LiteralPath $windowExe)) {
+27 -8
View File
@@ -276,7 +276,8 @@ function installWindowsDeps(bundle) {
log('deps', 'npm ci --omit=dev --os=win32 --cpu=x64 (sharp win32-x64 prebuild)'); log('deps', 'npm ci --omit=dev --os=win32 --cpu=x64 (sharp win32-x64 prebuild)');
// --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the // --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the
// prebuilt binary through optionalDependencies, and running a Windows-only // prebuilt binary through optionalDependencies, and running a Windows-only
// script on the build host would fail for no reason. // script on the build host would fail for no reason. The ONNX skip keeps the
// postinstall from downloading the CUDA build; CPU binaries ship in the package.
run( run(
NPM, NPM,
[ [
@@ -289,6 +290,7 @@ function installWindowsDeps(bundle) {
'--ignore-scripts', '--ignore-scripts',
], ],
appDir, appDir,
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
); );
// .bin shims are for a shell, not for `node server/index.mjs`; on a Linux // .bin shims are for a shell, not for `node server/index.mjs`; on a Linux
// build they would also be POSIX symlinks inside the zip. // build they would also be POSIX symlinks inside the zip.
@@ -443,6 +445,19 @@ function writeVersion(bundle, pkg, launcher, nodeVersion, nodeHash, nodeSize) {
function writeBundleReadme(bundle, info) { function writeBundleReadme(bundle, info) {
const start = info.launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd (or Luminary.vbs for no console window)'; const start = info.launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd (or Luminary.vbs for no console window)';
const windowLine = info.nativeWindow
? 'Window: opens in its own window: no browser, no tabs, no address bar, and\n' +
' no Edge profile or Microsoft account'
: 'Window: opens in a chromeless Edge/Chrome window; "Luminary.cmd -Browser"\n' +
' for a normal tab';
const windowRequirement = info.nativeWindow
? ' - The Microsoft Edge WebView2 runtime, which Windows 10 and 11 install with\n' +
' Edge. It is the window engine only: no browser is opened and no Edge\n' +
' profile, account or synced settings are used. If it is missing the window\n' +
' says so and links to the one-time download.\n' +
' - WebGL2 for the Develop module (WebView2 provides it).'
: ' - A current browser (Edge, Chrome or Firefox) with WebGL2 for the Develop\n' +
' module.';
const body = `Luminary ${info.version} for Windows (x64) — portable bundle const body = `Luminary ${info.version} for Windows (x64) — portable bundle
================================================= =================================================
@@ -454,13 +469,13 @@ Logs: logs\\server.out.log and logs\\server.err.log
Check: "Luminary.cmd -Verify" lists the files a complete bundle needs Check: "Luminary.cmd -Verify" lists the files a complete bundle needs
Repair: "Luminary.cmd -Repair" downloads node.exe again and verifies its sha256 Repair: "Luminary.cmd -Repair" downloads node.exe again and verifies its sha256
Sign-in: none — single-user desktop mode, no account setup Sign-in: none — single-user desktop mode, no account setup
Window: opens in its own window (native when bundled, else chromeless Edge/Chrome); Network: not needed — the app and its service run on this PC, so it starts
"Luminary.cmd -Browser" for a normal tab and runs with the network disconnected
${windowLine}
Requirements Requirements
- Windows 10 or 11, 64-bit. - Windows 10 or 11, 64-bit.
- A current browser (Edge, Chrome or Firefox) with WebGL2 for the Develop ${windowRequirement}
module.
- Nothing else. Node.js is included as node.exe, and no .NET, Visual C++ - Nothing else. Node.js is included as node.exe, and no .NET, Visual C++
Redistributable, admin rights or installer is needed. Redistributable, admin rights or installer is needed.
- About 250 MB free where the data folder lives. - About 250 MB free where the data folder lives.
@@ -488,8 +503,9 @@ Notes
opens signed in. It is not meant for several people sharing one Windows opens signed in. It is not meant for several people sharing one Windows
login with separate accounts. login with separate accounts.
- The bundle is unsigned, so SmartScreen may ask once ("More info" -> "Run anyway"). - The bundle is unsigned, so SmartScreen may ask once ("More info" -> "Run anyway").
- The server listens on 127.0.0.1 only. Set HOST=0.0.0.0 before starting if - The local engine listens on 127.0.0.1 only: it is a background service on
client proofing galleries must be reachable from other devices on the LAN. this PC. Set HOST=0.0.0.0 before starting only if client proofing galleries
must be reachable from other devices on the LAN.
- RAW decoding uses the bundled libraw WebAssembly; sharp's Windows prebuilt - RAW decoding uses the bundled libraw WebAssembly; sharp's Windows prebuilt
binary is included, so there is nothing else to install. binary is included, so there is nothing else to install.
`; `;
@@ -649,6 +665,9 @@ async function fetchMakensis(outDir) {
const root = path.join(outDir, 'tools', 'nsis'); const root = path.join(outDir, 'tools', 'nsis');
mkdirSync(debs, { recursive: true }); mkdirSync(debs, { recursive: true });
rmSync(root, { recursive: true, force: true }); rmSync(root, { recursive: true, force: true });
// dpkg-deb -x creates the destination itself but not its parents, and a
// fresh --out has no tools/ yet.
mkdirSync(root, { recursive: true });
for (const name of [`nsis_${packVersion}_amd64.deb`, `nsis-common_${packVersion}_all.deb`]) { for (const name of [`nsis_${packVersion}_amd64.deb`, `nsis-common_${packVersion}_all.deb`]) {
const file = path.join(debs, name); const file = path.join(debs, name);
if (!existsSync(file)) { if (!existsSync(file)) {
@@ -774,7 +793,7 @@ async function main() {
} }
const info = writeVersion(bundle, pkg, launcher, options.node, node.hash, statSync(bundledNode).size); const info = writeVersion(bundle, pkg, launcher, options.node, node.hash, statSync(bundledNode).size);
writeBundleReadme(bundle, { ...info, launcher }); writeBundleReadme(bundle, { ...info, launcher, nativeWindow: Boolean(options.webview2) });
const zipPath = path.join(options.out, `Luminary-${pkg.version}-win-x64.zip`); const zipPath = path.join(options.out, `Luminary-${pkg.version}-win-x64.zip`);
rmSync(zipPath, { force: true }); rmSync(zipPath, { force: true });
+28 -17
View File
@@ -81,12 +81,27 @@ VIAddVersionKey "LegalCopyright" "MIT licensed"
!define MUI_FINISHPAGE_SHOWREADME_TEXT "Show the Windows readme" !define MUI_FINISHPAGE_SHOWREADME_TEXT "Show the Windows readme"
!define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED !define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED
!if /FileExists "${SOURCE_DIR}/Luminary.vbs" ; The native launcher first: it needs no Windows Script Host (which group
!define MUI_FINISHPAGE_RUN "$INSTDIR\Luminary.vbs" ; policy can disable, leaving "Start Luminary" doing nothing) and opens no
; console. The .vbs, then the .cmd, are only fallbacks for old bundles.
!if /FileExists "${SOURCE_DIR}/Luminary.exe"
!define APP_LAUNCH "$INSTDIR\Luminary.exe"
!else !else
!define MUI_FINISHPAGE_RUN "$INSTDIR\Luminary.cmd" !if /FileExists "${SOURCE_DIR}/Luminary.vbs"
!define APP_LAUNCH "$INSTDIR\Luminary.vbs"
!else
!define APP_LAUNCH "$INSTDIR\Luminary.cmd"
!endif
!endif !endif
!define MUI_FINISHPAGE_RUN "${APP_LAUNCH}"
!define MUI_FINISHPAGE_RUN_TEXT "Start ${APP_NAME}" !define MUI_FINISHPAGE_RUN_TEXT "Start ${APP_NAME}"
; MUI starts the finish-page target with Exec, which hands the path straight to
; CreateProcess. That only works for a real executable: when the bundle ships
; the PowerShell launcher (no Go toolchain at build time) the target is
; Luminary.vbs, and CreateProcess cannot start a script, so the ticked "Start
; Luminary" box closed the installer and nothing opened. ExecShell goes through
; the shell, so the exe, the .vbs and the .cmd all start.
!define MUI_FINISHPAGE_RUN_FUNCTION "StartLuminaryOnFinish"
!insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_WELCOME
!if /FileExists "${SOURCE_DIR}/LICENSE" !if /FileExists "${SOURCE_DIR}/LICENSE"
@@ -106,6 +121,10 @@ LangString DESC_Main ${LANG_ENGLISH} "The editor, film looks, bundled Node runti
LangString DESC_Desktop ${LANG_ENGLISH} "Put a Luminary shortcut on the desktop." LangString DESC_Desktop ${LANG_ENGLISH} "Put a Luminary shortcut on the desktop."
LangString DESC_Startup ${LANG_ENGLISH} "Start Luminary in the background when you sign in to Windows." LangString DESC_Startup ${LANG_ENGLISH} "Start Luminary in the background when you sign in to Windows."
Function StartLuminaryOnFinish
ExecShell "open" "${APP_LAUNCH}"
FunctionEnd
Function .onInit Function .onInit
; The launcher refuses these too, but the installer should say so before it ; The launcher refuses these too, but the installer should say so before it
; copies 250 MB onto an unsupported PC. ; copies 250 MB onto an unsupported PC.
@@ -143,12 +162,12 @@ Section "Luminary (required)" SEC_MAIN
WriteUninstaller "$INSTDIR\Uninstall.exe" WriteUninstaller "$INSTDIR\Uninstall.exe"
CreateDirectory "$SMPROGRAMS\Luminary" CreateDirectory "$SMPROGRAMS\Luminary"
!if /FileExists "${SOURCE_DIR}/Luminary.vbs" CreateShortCut "$SMPROGRAMS\Luminary\Luminary.lnk" "${APP_LAUNCH}" "" "$INSTDIR\Luminary.ico" 0
CreateShortCut "$SMPROGRAMS\Luminary\Luminary.lnk" "$INSTDIR\Luminary.vbs" "" "$INSTDIR\Luminary.ico" 0 !if /FileExists "${SOURCE_DIR}/Luminary.exe"
CreateShortCut "$SMPROGRAMS\Luminary\Stop Luminary.lnk" "$INSTDIR\Luminary.exe" "-Stop" "$INSTDIR\Luminary.ico" 0
!else !else
CreateShortCut "$SMPROGRAMS\Luminary\Luminary.lnk" "$INSTDIR\Luminary.cmd" "" "$INSTDIR\Luminary.ico" 0 CreateShortCut "$SMPROGRAMS\Luminary\Stop Luminary.lnk" "$INSTDIR\Stop Luminary.cmd" "" "$INSTDIR\Luminary.ico" 0
!endif !endif
CreateShortCut "$SMPROGRAMS\Luminary\Stop Luminary.lnk" "$INSTDIR\Stop Luminary.cmd" "" "$INSTDIR\Luminary.ico" 0
CreateShortCut "$SMPROGRAMS\Luminary\Luminary data folder.lnk" "$LOCALAPPDATA\Luminary\data" "" "$INSTDIR\Luminary.ico" 0 CreateShortCut "$SMPROGRAMS\Luminary\Luminary data folder.lnk" "$LOCALAPPDATA\Luminary\data" "" "$INSTDIR\Luminary.ico" 0
WriteRegStr HKCU "${APP_KEY}" "InstallDir" "$INSTDIR" WriteRegStr HKCU "${APP_KEY}" "InstallDir" "$INSTDIR"
@@ -168,19 +187,11 @@ Section "Luminary (required)" SEC_MAIN
SectionEnd SectionEnd
Section "Desktop shortcut" SEC_DESKTOP Section "Desktop shortcut" SEC_DESKTOP
!if /FileExists "${SOURCE_DIR}/Luminary.vbs" CreateShortCut "$DESKTOP\Luminary.lnk" "${APP_LAUNCH}" "" "$INSTDIR\Luminary.ico" 0
CreateShortCut "$DESKTOP\Luminary.lnk" "$INSTDIR\Luminary.vbs" "" "$INSTDIR\Luminary.ico" 0
!else
CreateShortCut "$DESKTOP\Luminary.lnk" "$INSTDIR\Luminary.cmd" "" "$INSTDIR\Luminary.ico" 0
!endif
SectionEnd SectionEnd
Section "Start Luminary when I sign in" SEC_STARTUP Section "Start Luminary when I sign in" SEC_STARTUP
!if /FileExists "${SOURCE_DIR}/Luminary.vbs" WriteRegStr HKCU "${RUN_KEY}" "Luminary" '"${APP_LAUNCH}"'
WriteRegStr HKCU "${RUN_KEY}" "Luminary" '"$INSTDIR\Luminary.vbs"'
!else
WriteRegStr HKCU "${RUN_KEY}" "Luminary" '"$INSTDIR\Luminary.cmd"'
!endif
SectionEnd SectionEnd
!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
+7 -2
View File
@@ -142,8 +142,13 @@ create data dir → create log dir → pick port → spawn node.exe (hidden)
second or third attempt). second or third attempt).
- The PowerShell launcher checks `$process.HasExited` first, so a crash reports - The PowerShell launcher checks `$process.HasExited` first, so a crash reports
the log instead of waiting the full timeout. the log instead of waiting the full timeout.
- The browser is opened only after health succeeds; opening earlier shows a - The probe is a raw HTTP request over TCP to `127.0.0.1`, in both launchers,
connection error on slow machines. and never `Invoke-WebRequest` or a proxy-aware HTTP client. WinINET resolves
the system proxy (a PAC script or WPAD) before it looks at the URL, which can
block for far longer than the request timeout on a machine with no network;
the server was healthy the whole time, but every probe timed out and the
launcher reported that Luminary had not started. Start-up must never depend on
a connection, a proxy setting or DNS.
Logs are append-only: `logs\server.out.log` and `logs\server.err.log` from the Logs are append-only: `logs\server.out.log` and `logs\server.err.log` from the
child, `logs\launcher.log` from the Go launcher. They fall back to child, `logs\launcher.log` from the Go launcher. They fall back to
+69 -18
View File
@@ -3,15 +3,15 @@
This is the no-toolchain launcher: it ships in every bundle and is what This is the no-toolchain launcher: it ships in every bundle and is what
Luminary.exe replaces when a Go build is available. It owns the three things Luminary.exe replaces when a Go build is available. It owns the three things
the server deliberately does not do for itself: Luminary's local engine deliberately does not do for itself:
1. Pick a free loopback port and pass it as PORT. 1. Pick a free loopback port and pass it as PORT.
2. Start node.exe hidden with LUMINARY_DATA outside the bundle. 2. Start node.exe hidden with LUMINARY_DATA outside the bundle.
3. Wait for /api/health before opening the browser. 3. Wait for /api/health before opening the browser.
Usage: Usage:
Luminary.ps1 start (or reuse) the server and open the browser Luminary.ps1 start (or reuse) the local engine and open the browser
Luminary.ps1 -Stop stop the server started from this folder Luminary.ps1 -Stop stop the local engine started from this folder
Luminary.ps1 -Status report what is running and where the data lives Luminary.ps1 -Status report what is running and where the data lives
Luminary.ps1 -Verify list the files the bundle must contain Luminary.ps1 -Verify list the files the bundle must contain
Luminary.ps1 -Repair re-download node.exe and check it against version.txt Luminary.ps1 -Repair re-download node.exe and check it against version.txt
@@ -96,11 +96,34 @@ function Read-Runtime {
try { return Get-Content -Raw -LiteralPath $runtimeFile | ConvertFrom-Json } catch { return $null } try { return Get-Content -Raw -LiteralPath $runtimeFile | ConvertFrom-Json } catch { return $null }
} }
# Loopback liveness probe.
#
# Invoke-WebRequest goes through WinINET, which resolves the system proxy (a PAC
# script or WPAD) before it looks at the URL. On a machine with no network that
# lookup can block for far longer than -TimeoutSec, so every probe timed out and
# the launcher killed a healthy local engine: the app "would not start" offline.
# A raw request over TCP to 127.0.0.1 uses no proxy, DNS or certificate store, so
# start-up behaves the same with or without a connection.
function Test-Health([int]$port) { function Test-Health([int]$port) {
$client = $null
try { try {
$response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 2 -Uri ("http://127.0.0.1:{0}/api/health" -f $port) $client = New-Object System.Net.Sockets.TcpClient
return ($response.StatusCode -eq 200) $connect = $client.ConnectAsync([System.Net.IPAddress]::Loopback, $port)
} catch { return $false } if (-not $connect.Wait(2000)) { return $false }
$client.ReceiveTimeout = 3000
$stream = $client.GetStream()
$request = [System.Text.Encoding]::ASCII.GetBytes((
"GET /api/health HTTP/1.0`r`nHost: 127.0.0.1:{0}`r`nConnection: close`r`n`r`n" -f $port))
$stream.Write($request, 0, $request.Length)
$stream.Flush()
$reader = New-Object System.IO.StreamReader($stream, [System.Text.Encoding]::ASCII)
$status = $reader.ReadLine()
return ($status -match '^HTTP/1\.[01] 200\b')
} catch {
return $false
} finally {
if ($client) { $client.Close() }
}
} }
function Test-Process([int]$processId) { function Test-Process([int]$processId) {
@@ -133,8 +156,20 @@ function Open-Browser([string]$url) {
# Edge is part of Windows 10/11, so a chromeless app window costs no extra # Edge is part of Windows 10/11, so a chromeless app window costs no extra
# runtime. Chrome is the second choice; anything else falls back to a tab. # runtime. Chrome is the second choice; anything else falls back to a tab.
# Chrome first, then Edge: both are Chromium, but Edge's first run asks for a
# Microsoft account and starts syncing settings, which reads as an unwanted
# browser taking over the machine.
function Find-AppWindowBrowser { function Find-AppWindowBrowser {
$candidates = @() $candidates = @()
if ($env:LOCALAPPDATA) {
$candidates += (Join-Path $env:LOCALAPPDATA 'Google\Chrome\Application\chrome.exe')
}
if ($env:ProgramFiles) {
$candidates += (Join-Path $env:ProgramFiles 'Google\Chrome\Application\chrome.exe')
}
if (${env:ProgramFiles(x86)}) {
$candidates += (Join-Path ${env:ProgramFiles(x86)} 'Google\Chrome\Application\chrome.exe')
}
if (${env:ProgramFiles(x86)}) { if (${env:ProgramFiles(x86)}) {
$candidates += (Join-Path ${env:ProgramFiles(x86)} 'Microsoft\Edge\Application\msedge.exe') $candidates += (Join-Path ${env:ProgramFiles(x86)} 'Microsoft\Edge\Application\msedge.exe')
} }
@@ -143,13 +178,6 @@ function Find-AppWindowBrowser {
} }
if ($env:LOCALAPPDATA) { if ($env:LOCALAPPDATA) {
$candidates += (Join-Path $env:LOCALAPPDATA 'Microsoft\Edge\Application\msedge.exe') $candidates += (Join-Path $env:LOCALAPPDATA 'Microsoft\Edge\Application\msedge.exe')
$candidates += (Join-Path $env:LOCALAPPDATA 'Google\Chrome\Application\chrome.exe')
}
if ($env:ProgramFiles) {
$candidates += (Join-Path $env:ProgramFiles 'Google\Chrome\Application\chrome.exe')
}
if (${env:ProgramFiles(x86)}) {
$candidates += (Join-Path ${env:ProgramFiles(x86)} 'Google\Chrome\Application\chrome.exe')
} }
foreach ($candidate in $candidates) { foreach ($candidate in $candidates) {
if ($candidate -and (Test-Path -LiteralPath $candidate)) { return $candidate } if ($candidate -and (Test-Path -LiteralPath $candidate)) { return $candidate }
@@ -183,12 +211,16 @@ function Open-App([string]$url) {
$profile = Join-Path (Get-DataDir) 'window-profile' $profile = Join-Path (Get-DataDir) 'window-profile'
try { try {
New-Item -ItemType Directory -Force -Path $profile | Out-Null New-Item -ItemType Directory -Force -Path $profile | Out-Null
# --no-proxy-server: the window only ever loads 127.0.0.1. A proxy or PAC
# script set on the machine must not be able to intercept (or stall) it
# when the network is down.
Start-Process -FilePath $exe -ArgumentList @( Start-Process -FilePath $exe -ArgumentList @(
"--app=$url", "--app=$url",
"--user-data-dir=$profile", "--user-data-dir=$profile",
'--window-size=1500,950', '--window-size=1500,950',
'--no-first-run', '--no-first-run',
'--no-default-browser-check', '--no-default-browser-check',
'--no-proxy-server',
'--disable-features=Translate' '--disable-features=Translate'
) | Out-Null ) | Out-Null
} catch { } catch {
@@ -207,6 +239,25 @@ function Get-WindowsBuild {
# node.exe ships with it (and -Repair re-downloads it), libvips needs only the # node.exe ships with it (and -Repair re-downloads it), libvips needs only the
# Universal C Runtime that Windows 10/11 already has, and no admin rights are # Universal C Runtime that Windows 10/11 already has, and no admin rights are
# involved. Verified against the PE imports of node.exe and libvips-42.dll. # involved. Verified against the PE imports of node.exe and libvips-42.dll.
# The architecture of the machine, not of this process. Started from a 32-bit
# parent - the setup's finish page, or a SysWOW64 shell - a 64-bit PC still
# reports PROCESSOR_ARCHITECTURE=x86; the real value is in the WOW64 copy, and
# Is64BitOperatingSystem settles it.
function Get-MachineArch {
$arch = $env:PROCESSOR_ARCHITEW6432
if (-not $arch) { $arch = $env:PROCESSOR_ARCHITECTURE }
$is64 = $false
try { $is64 = [Environment]::Is64BitOperatingSystem } catch { }
if (-not $arch) { $arch = if ($is64) { 'AMD64' } else { 'x86' } }
if ($is64) {
if ($arch -eq 'x86') { $arch = 'AMD64' }
} elseif ($arch -eq 'AMD64' -or $arch -eq 'ARM64') {
# The OS says 32-bit; believe it rather than a stale variable.
$arch = 'x86'
}
return $arch
}
function Test-Platform { function Test-Platform {
$problems = @() $problems = @()
$notes = @() $notes = @()
@@ -216,7 +267,7 @@ function Test-Platform {
$problems += ("Luminary needs Windows 10 or 11. This PC reports build {0}." -f $build) $problems += ("Luminary needs Windows 10 or 11. This PC reports build {0}." -f $build)
} }
$arch = $env:PROCESSOR_ARCHITECTURE $arch = Get-MachineArch
if ($arch -and $arch -ne 'AMD64' -and $arch -ne 'ARM64') { if ($arch -and $arch -ne 'AMD64' -and $arch -ne 'ARM64') {
$problems += ("Luminary ships a 64-bit runtime; this PC reports '{0}'." -f $arch) $problems += ("Luminary ships a 64-bit runtime; this PC reports '{0}'." -f $arch)
} elseif ($arch -eq 'ARM64') { } elseif ($arch -eq 'ARM64') {
@@ -489,7 +540,7 @@ if ($Status) {
Write-Host 'Luminary is not running.' Write-Host 'Luminary is not running.'
} }
$platform = Test-Platform $platform = Test-Platform
Write-Host ("System: Windows build {0}, {1}" -f (Get-WindowsBuild), $env:PROCESSOR_ARCHITECTURE) Write-Host ("System: Windows build {0}, {1}" -f (Get-WindowsBuild), (Get-MachineArch))
foreach ($note in $platform.notes) { Write-Host ("Note: {0}" -f $note) } foreach ($note in $platform.notes) { Write-Host ("Note: {0}" -f $note) }
foreach ($problem in $platform.problems) { Write-Host ("Problem: {0}" -f $problem) } foreach ($problem in $platform.problems) { Write-Host ("Problem: {0}" -f $problem) }
$node = Resolve-Node $node = Resolve-Node
@@ -534,7 +585,7 @@ if ($running) {
} }
if (Test-Process ([int]$runtime.pid)) { if (Test-Process ([int]$runtime.pid)) {
$logNote = Join-Path (Get-DataDir) 'logs' $logNote = Join-Path (Get-DataDir) 'logs'
Show-ErrorDialog ("Luminary has been starting for over two minutes and is not answering on port {0}.`n`nSee {1} for the server log." -f $runtime.port, $logNote) Show-ErrorDialog ("Luminary has been starting for over two minutes and is not answering on its local port {0}.`n`nSee {1} for the log." -f $runtime.port, $logNote)
exit 1 exit 1
} }
} }
@@ -598,7 +649,7 @@ $logsOut = Get-LogDir $dataDir
$port = Find-Port $port = Find-Port
$url = "http://127.0.0.1:$port" $url = "http://127.0.0.1:$port"
# The server reads these from the environment; nothing is written into app\. # The local engine reads these from the environment; nothing is written into app\.
$env:PORT = "$port" $env:PORT = "$port"
$env:HOST = '127.0.0.1' $env:HOST = '127.0.0.1'
$env:NODE_ENV = 'production' $env:NODE_ENV = 'production'
@@ -640,7 +691,7 @@ while ((Get-Date) -lt $deadline) {
$tail = '' $tail = ''
if (Test-Path -LiteralPath $errLog) { $tail = (Get-Content -LiteralPath $errLog -Tail 20) -join "`n" } if (Test-Path -LiteralPath $errLog) { $tail = (Get-Content -LiteralPath $errLog -Tail 20) -join "`n" }
Write-Host 'Luminary did not answer on /api/health.' Write-Host "Luminary's local engine did not answer."
if ($tail) { Write-Host $tail } if ($tail) { Write-Host $tail }
if (-not $process.HasExited) { & taskkill.exe /PID $process.Id /T /F | Out-Null } if (-not $process.HasExited) { & taskkill.exe /PID $process.Id /T /F | Out-Null }
Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue
+1 -1
View File
@@ -1,4 +1,4 @@
@echo off @echo off
rem Stop the Luminary server started from this folder. rem Stop the Luminary local engine started from this folder.
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Luminary.ps1" -Stop powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Luminary.ps1" -Stop
pause pause
+29 -13
View File
@@ -9,8 +9,8 @@
// //
// Usage: // Usage:
// //
// Luminary.exe start (or reuse) the server and open the browser // Luminary.exe start (or reuse) the local engine and open the browser
// Luminary.exe -stop stop the server started from this folder // Luminary.exe -stop stop the local engine started from this folder
// Luminary.exe -repair re-download node.exe and verify it against version.txt // Luminary.exe -repair re-download node.exe and verify it against version.txt
// //
// The design and the edge cases are described in ../DESIGN.md. // The design and the edge cases are described in ../DESIGN.md.
@@ -58,7 +58,17 @@ var (
user32 = syscall.NewLazyDLL("user32.dll") user32 = syscall.NewLazyDLL("user32.dll")
messageBoxW = user32.NewProc("MessageBoxW") messageBoxW = user32.NewProc("MessageBoxW")
client = &http.Client{Timeout: 2 * time.Second} // Health is a loopback call: no proxy, no DNS, no internet. The default
// transport honours HTTP_PROXY, so a stale corporate proxy or PAC script
// would make every probe fail and the launcher would kill a server that was
// already answering.
client = &http.Client{
Timeout: 2 * time.Second,
Transport: &http.Transport{
Proxy: nil,
DialContext: (&net.Dialer{Timeout: 2 * time.Second}).DialContext,
},
}
downloadClient = &http.Client{Timeout: 10 * time.Minute} downloadClient = &http.Client{Timeout: 10 * time.Minute}
nodePinRE = regexp.MustCompile(`^node\s+v?(\d+\.\d+\.\d+)\s+win-x64(?:\s+sha256\s+([0-9a-f]{64}))?(?:\s+size\s+(\d+))?`) nodePinRE = regexp.MustCompile(`^node\s+v?(\d+\.\d+\.\d+)\s+win-x64(?:\s+sha256\s+([0-9a-f]{64}))?(?:\s+size\s+(\d+))?`)
) )
@@ -222,8 +232,8 @@ func run() error {
time.Sleep(pollEvery) time.Sleep(pollEvery)
} }
if processAlive(info.PID) { if processAlive(info.PID) {
return fmt.Errorf("Luminary is already starting (pid %d) but is not answering on port %d. "+ return fmt.Errorf("Luminary is already starting (pid %d) but is not answering on its "+
"See %s.", info.PID, info.Port, filepath.Join(dataDirectory(), "logs", "server.err.log")) "local port %d. See %s.", info.PID, info.Port, filepath.Join(dataDirectory(), "logs", "server.err.log"))
} }
} }
} }
@@ -291,7 +301,7 @@ func run() error {
// code is deliberately ignored: "Stop" force-kills the child. // code is deliberately ignored: "Stop" force-kills the child.
_ = cmd.Wait() _ = cmd.Wait()
removeRuntime() removeRuntime()
writeLog("launcher.log", "server exited") writeLog("launcher.log", "local engine exited")
return nil return nil
} }
time.Sleep(pollEvery) time.Sleep(pollEvery)
@@ -299,8 +309,8 @@ func run() error {
_ = cmd.Process.Kill() _ = cmd.Process.Kill()
removeRuntime() removeRuntime()
return fmt.Errorf("Luminary did not answer on %s within %s; see %s", return fmt.Errorf("Luminary's local engine did not answer within %s; see %s",
healthPath, startupWait, filepath.Join(logDir, "server.err.log")) startupWait, filepath.Join(logDir, "server.err.log"))
} }
// --- runtime resolution ------------------------------------------------------- // --- runtime resolution -------------------------------------------------------
@@ -572,8 +582,10 @@ func openBrowser(url string) {
_ = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() _ = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
} }
// Edge ships with Windows 10/11, so a chromeless app window costs no extra // Chrome comes first, then Edge: both are Chromium and cost no extra runtime,
// runtime. Chrome is the second choice; anything else falls back to a tab. // but starting Edge prompts for the Microsoft account and settings sync, which
// reads as an unwanted browser taking over the machine. Anything else falls
// back to a normal tab.
func findAppBrowser() string { func findAppBrowser() string {
candidates := []string{} candidates := []string{}
add := func(dir string, rest ...string) { add := func(dir string, rest ...string) {
@@ -581,12 +593,12 @@ func findAppBrowser() string {
candidates = append(candidates, filepath.Join(append([]string{dir}, rest...)...)) candidates = append(candidates, filepath.Join(append([]string{dir}, rest...)...))
} }
} }
for _, key := range []string{"ProgramFiles(x86)", "ProgramFiles", "LOCALAPPDATA"} {
add(os.Getenv(key), "Microsoft", "Edge", "Application", "msedge.exe")
}
for _, key := range []string{"LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"} { for _, key := range []string{"LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"} {
add(os.Getenv(key), "Google", "Chrome", "Application", "chrome.exe") add(os.Getenv(key), "Google", "Chrome", "Application", "chrome.exe")
} }
for _, key := range []string{"ProgramFiles(x86)", "ProgramFiles", "LOCALAPPDATA"} {
add(os.Getenv(key), "Microsoft", "Edge", "Application", "msedge.exe")
}
for _, candidate := range candidates { for _, candidate := range candidates {
if info, err := os.Stat(candidate); err == nil && info.Size() > 0 { if info, err := os.Stat(candidate); err == nil && info.Size() > 0 {
return candidate return candidate
@@ -621,12 +633,16 @@ func openApp(url string) {
openBrowser(url) openBrowser(url)
return return
} }
// --no-proxy-server: the window only ever loads 127.0.0.1, so a proxy or
// PAC script on the machine must not intercept or stall it when the
// network is down.
cmd := exec.Command(exe, cmd := exec.Command(exe,
"--app="+url, "--app="+url,
"--user-data-dir="+profile, "--user-data-dir="+profile,
"--window-size=1500,950", "--window-size=1500,950",
"--no-first-run", "--no-first-run",
"--no-default-browser-check", "--no-default-browser-check",
"--no-proxy-server",
"--disable-features=Translate", "--disable-features=Translate",
) )
if err := cmd.Start(); err != nil { if err := cmd.Start(); err != nil {
+9 -8
View File
@@ -7,8 +7,8 @@ app never looks in this folder.
| File | What to do with it | | File | What to do with it |
| --- | --- | | --- | --- |
| `Luminary-<version>-win-x64-setup.exe` | Copy to the Windows PC and run it. Per-user install, no admin prompt: Start-menu shortcuts, optional desktop shortcut and start-at-login, and an uninstaller that keeps `%LOCALAPPDATA%\Luminary\data`. | | `Luminary-<version>-win-x64-setup.exe` | Copy to the Windows PC and run it. Per-user install, no admin prompt: Start-menu shortcuts, optional desktop shortcut and start-at-login, and an uninstaller that keeps `%LOCALAPPDATA%\Luminary\data`. |
| `Luminary-<version>-win-x64.zip` | The portable alternative: extract, then run `Luminary.cmd` (or `Luminary.vbs`) from the extracted `Luminary` folder. `README-windows.txt` inside the zip is the end-user guide. | | `Luminary-<version>-win-x64.zip` | The portable alternative: extract, then run `Luminary.exe` from the extracted `Luminary` folder. `README-windows.txt` inside the zip is the end-user guide. |
| `LuminaryWindow.exe` inside the zip | optional native window (WebView2); the launcher uses it automatically when present, and starting it directly forwards to the launcher | | `LuminaryWindow.exe` inside the zip | the app window (WebView2): no browser is opened, so it cannot pull in an Edge profile or Microsoft account. The launcher uses it automatically, and starting it directly forwards to the launcher |
| `SHA256SUMS.txt` | Check a copy did not corrupt: `certutil -hashfile Luminary-<version>-win-x64-setup.exe SHA256` | | `SHA256SUMS.txt` | Check a copy did not corrupt: `certutil -hashfile Luminary-<version>-win-x64-setup.exe SHA256` |
## Rebuilding this folder ## Rebuilding this folder
@@ -24,7 +24,7 @@ stages and zips **outside** the checkout (`~/.cache/luminary-windows`, or
artifact. Old versions are not deleted, so remove the ones you no longer ship. artifact. Old versions are not deleted, so remove the ones you no longer ship.
Add `--webview2 <path to LuminaryWindow.exe>` for the native window; without it Add `--webview2 <path to LuminaryWindow.exe>` for the native window; without it
the zip is about half the size (49 MB) and uses the Edge/Chrome app window. the zip is about 65 MB smaller and falls back to an Edge/Chrome app window.
## Before a deploy ## Before a deploy
@@ -35,8 +35,9 @@ publish only when you are actually shipping a build.
## What a Windows user needs ## What a Windows user needs
Windows 10/11 x64 and a current browser (Edge, Chrome or Firefox) with WebGL2. Windows 10/11 x64. Node.js, .NET and the Visual C++ Redistributable are **not**
Node.js, .NET and the Visual C++ Redistributable are **not** required — they are required — they are bundled or part of Windows. The app window uses the
bundled or part of Windows. The native window needs the Microsoft Edge WebView2 Microsoft Edge WebView2 runtime, which Windows 10/11 install with Edge; it is
runtime, which Windows 10/11 already has alongside Edge. See `../README.md` for the window engine only, so no browser window, profile or account is used. The
the import-level audit. Develop module needs WebGL2, which WebView2 provides. See `../README.md` for the
import-level audit.
+9 -1
View File
@@ -1,2 +1,10 @@
22b8943d1ca3bed3ef115530831947e4e03f6a45317ec6b35c10e871fad22a9a Luminary-0.5.1-win-x64.zip
b33e3d8b595aa3ff20b0898f3adea639e02afe9eb54c4fba5dd09ec07e041a0c Luminary-0.5.1-win-x64-setup.exe b33e3d8b595aa3ff20b0898f3adea639e02afe9eb54c4fba5dd09ec07e041a0c Luminary-0.5.1-win-x64-setup.exe
22b8943d1ca3bed3ef115530831947e4e03f6a45317ec6b35c10e871fad22a9a Luminary-0.5.1-win-x64.zip
c95ae4d21dfd80cd6206fc3f276c1d1d6afa61f55d48e6646f65784b483ca590 Luminary-0.5.2-win-x64-setup.exe
e81cbe4001bef43f79a2200acecc5dafbcf6c3c04dc2f6db4685f1f0b3ba3cdc Luminary-0.5.2-win-x64.zip
3e5a120b6d7483e0bdc6fb9091cf02e4bbab49e57e4d39c433521fb6ddf44b5a Luminary-0.5.3.1-win-x64-setup.exe
f4cd3e4a40dc79d9fb9d0d3dc627f317d33955cc9d6c77c5ee5f8bcb843b9a58 Luminary-0.5.3.1-win-x64.zip
97cceb61bba34733013d21e1fe240f39da790843694e1390f6266aa128f1c456 Luminary-0.5.4-win-x64-setup.exe
16d033a863345542a07e65bb3914f63d35432fe7b88c33cc65f9d7634428ab98 Luminary-0.5.4-win-x64.zip
44ba60f6bebf5a43e1f8bd2e9beba1b8636e59dc8d07ae9d43096d3b09992e53 Luminary-0.5.4.1-win-x64-setup.exe
2e2ebfcee53edfcb14a58a5535fd384dd99f6c7a386de7f9c59419e8fe6c7969 Luminary-0.5.4.1-win-x64.zip