diff --git a/CHANGELOG.md b/CHANGELOG.md index 892fe815..804e0f04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ All notable changes to formlit. Versions are `v*.*.*`; each release lists what it added, what it fixed and what is not verified yet. +## v0.54.0 · 2026-11-19 + +- Fixed: when formlit cannot start, it says why before it closes. The message gives the reason in a sentence (its engine program is missing, could not be started, stopped, or did not answer in time), the engine's last lines, and where the engine's log is. Before, a failed start showed one fixed sentence or closed with nothing at all. +- Fixed: quitting formlit on Windows ends its engine and everything the engine started, also when formlit is ended from Task Manager. On every system the engine now stops by itself within a few seconds once the app that started it is gone. +- Fixed: an engine left running without its app no longer blocks the next start. The new start ends it and takes over. +- Changed: a second formlit on the same data folder is refused with a sentence that names the folder and the running engine, instead of two engines writing to one catalog. +- Changed: opening the engine program by itself opens formlit instead of starting an engine nobody can see. If formlit is not beside it, it says so and stops. +- Added: the engine keeps a log, `Logs/formlit-engine.log` in the data folder (`~/Formlit` unless you chose another), with a second file for errors when it has no console to write them to. +- Changed: formlit waits up to two minutes for its engine to start, then says so. Before, it waited without end. +- Known: an engine left behind by 0.53.0 or older is not ended by the first start after the update, because older engines kept no record of themselves. It is gone after a restart of the computer, or when you end `formlit-engine` yourself. +- Known: a second start of formlit while it is open does not bring the open window forward yet. The second one closes with the sentence above. +- Checked here, on Linux only: the engine's start and stop with stand-in programs in place of the app, and the desktop app's start-up code as far as it can be checked without building the app. Nothing was run on Windows or macOS, and the desktop app itself was not built on the machine this was written on. + ## v0.53.0 · 2026-11-19 - Added: Antigravity (Google's `agy` program) can run in a tab of the terminal panel beside Claude Code, Codex and Cursor, connected to formlit's tools the same way. The panel offers it when it is found on this computer; when it is not, its line in the panel's menu says where formlit looked and how to install it. diff --git a/README.md b/README.md index 2db7a353..eeafbe69 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@
-
+
diff --git a/SECURITY.md b/SECURITY.md
index a5246329..d5461380 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -7,7 +7,7 @@ check whether the problem is still there.
| Version | Supported |
| --- | --- |
-| 0.53.x (latest release) | Yes |
+| 0.54.x (latest release) | Yes |
| Anything older | No |
## Reporting a vulnerability
diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md
index 18655289..03215bf8 100644
--- a/backend/HASHOUT_LOG.md
+++ b/backend/HASHOUT_LOG.md
@@ -2,7 +2,7 @@
Living log of all comment content, explainers, rationale, TODOs and removed code for the engine. Source files stay comment-free; everything they would have said lives here, indexed. Read this first, then edit code surgically.
-Current build version: v0.53.0
+Current build version: v0.54.0
Last updated: 2026-11-17 · unreleased: overlay.sharpen views, missingModel on 409 answers with model choices, BiRefNet and SAM 2.1 base plus as the recommended selection models, removable and card flags on file roots and camera roots (#review-gaps); camera import, bundled Lensfun profiles and DCP checks merged from feat/camera-import-profiles (#camera-import-profiles). Before: 2026-11-11 · v0.51.3 a failed move to the Trash leaves no copy behind; a cached thumbnail or preview removed while it is read no longer fails the request; setup picks Python by the interpreter's own architecture, native first on Apple silicon (#v0-51-3). Before: 2026-11-10 · v0.51.2 the i18n review covers the demo strings; clean --all removes the venv on Windows whatever else is there; the MCP status names the engine's real port; chat and first messages that start with a dash reach Claude Code as text; FTP makes relative remote folders; eject after import works on Windows; tethered and auto-imported shots count {seq} on; virtual copies follow their master in a copying catalog import; agents install writes a valid Codex config on Windows; session settings find their photos on Windows; video exports check collisions under the name they write; exports stack with their own originals; Rename and Move commit the files that went through when one fails; TIFF orientation and planar TIFFs read one way; agents cannot change the consent and program preferences or open a demo through run_command; TIFF and DNG leave non-ASCII text out of their ASCII tags; Delete from Disk moves each file before it removes the photo (#v0-51-2). Before: 2026-11-10 · v0.51.1 no engine changes (version string only). Before: 2026-11-09 · v0.51.0 demo.open builds the three browser demos as new demo catalogs under Formlit/Demos (#demo-open), _switch_catalog takes publish. Before: 2026-11-07 · v0.50.0 the Form extension host (formext_host.py vendored, cmd_extensions, the extensions router, the files-route guard exemption for GET and HEAD, extensions_list and extension_command); v0.49.3 no backend changes (version string only); v0.49.2 no backend changes (version string only); v0.49.1 no backend changes (version string only); v0.49.0 no backend changes (version string only); 2026-11-05 · v0.48.0 the engine install makes its environment with the same Python choice as the rest of setup (3.13 or 3.12 on Intel Macs), and remakes one an Intel Mac made with 3.14; v0.47.9 the install picks Python 3.12 to 3.14 (3.13 on Intel Macs) and Intel Macs pin the last libraries with Intel builds; 2026-11-04 · v0.47.8 no engine changes (the folder-removal test looks the folder up by its resolved path, as the importer stores it, so it passes on macOS where the temp folder is under the /var symlink); v0.47.7 no engine changes (README in the Form family template, Mackin's #6, merged with main); v0.47.6 no engine changes (version string only); 2026-11-03 · v0.47.5 no engine changes (version string only); 2026-10-31 · v0.47.4 .js, .mjs and .css keep their types on Windows, ffmpeg arrives on first run, the Linux packages pull in the media plugins; 2026-10-30 · v0.47.3 no engine changes (Windows desktop build passes --config, macOS OpenCV pinned, .gitattributes); 2026-10-26 · v0.47.1 the family test suite, no engine changes; 2026-10-23 · v0.46.2 Intelligent Previews and Adaptable preset groups with every built-in id kept (builtin_id), five presets retuned; v0.46.1 no engine changes (releases move to formcompiler, version string only); v0.46.0 no engine changes (the app icon was redrawn, see the frontend log); v0.45.3 no engine changes (LCM DreamShaper and MI-GAN fills measured against LaMa in Remove and not kept; for MI-GAN the mask is 255 to keep, the hole is not blanked, and input must be sRGB: RESEARCH_GENFILL.md); v0.45.2 no engine changes (the SD 1.5 Detail pass was built, measured softer than LaMa and not kept: RESEARCH_GENFILL.md in the sidecar); v0.45.1 no engine changes (generative fill researched and not added: see the sidecar's RESEARCH_GENFILL.md); v0.45.0 Same Surface and Same Depth sample windows, develop.sampleDepth; v0.44.0 Keep Lines for Remove (lines_fill, keep_lines), brush Edge Snap; v0.43.0 control maps (ai.controlMaps, get_control_maps), Remove from the same surface; v0.42.2 no engine changes; v0.42.1 no engine changes; v0.42.0 678 researched presets (978 built in), preset zip packs and group export, Edge Range masks, Remove from the same depth; v0.41.1 no engine changes; v0.41.0 the learned style calibrates itself per control on the person's edits; v0.40.0 PDF/X-1a:2001 passing the preflight gem, Check My Style, the i18n review round trip; v0.39.0 PDF/X-1a with embedded fonts and a self-check, shadows hidden behind the subject; v0.38.0 per-window blend exposure, SFTP, freeze collects all modules, Remove sample-from area, low-sun shadows, CMYK books; v0.37.0 KDP inside margin by page count, proofing pick limit, Send by FTP after export; v0.36.0 Apply My Style (develop.applyStyle, apply_my_style), collapsed-stack filtering, describe smart rule, skin maxSize; v0.35.1 new imports indexed for search; v0.35.0 book PDFs for Lulu, Amazon KDP and IngramSpark; v0.34.1 no engine changes (its user-facing strings are in the window's translation catalogs); v0.34.0 remove controls (shadows and reflections, seeded Refresh, plainest first), remove_object; v0.33.0 flash and window blending, ai.flashBlend, merge_flash_blend; v0.32.0 batch skin retouching, retouch.skin, retouch_skin; v0.31.0 search by description and Find Similar (SigLIP), search.* commands, two MCP tools; v0.30.2 astro sky line at full size, landscape aligned when the camera moved; v0.30.1 astro alignment for wide lenses, checked on a real time-lapse; v0.30.0 client proofing without accounts, astro check on a real photo; v0.29.0 astro stacking; v0.28.0 sessions, settings kept in the session folder, rendered exports without the recipe, MCP session tools; v0.27.0 the learned denoiser (SCUNet); v0.26.3 edge points on AI masks, develop.maskOutline; v0.26.2 hair and skin parts from the parts model, each person apart with the instances model, fills on a crop; v0.26.1 the model features on their real models, four fixes; v0.26.0 skin-tone uniformity, develop.skinPick; v0.25.0 focus stacking; v0.24.0 adjustment layers, addLayer and setLayer; v0.23.0 refine, shift and feather on AI mask components, the refine op; v0.22.0 code replacements, caption variables, required fields; v0.21.0 per-face cull scores, cull.groups, get_cull_groups; v0.20.0 no engine changes; v0.19.0 chat token usage, tool-result images, chat.sessions and chat.adopt, claudecode.open resume; v0.18.0 no engine changes; v0.17.0 photo ids on chat tool events; v0.16.0 chat text, context and note, Stop verified; v0.15.0 the Chat tab's chat.* commands; v0.14.0 Claude Code settings from preferences; v0.13.0 no engine changes; v0.12.0 show_in_window reference; v0.11.0 shoot recipes, templates, noise reduction by ISO, export presets, {shoot} at import; v0.10.0 professional workflow prompts, pro ingest, Refine Photos, version tools, 300 presets; v0.9.1 face-part model requirement, empty masks refused, model pins verified; v0.9.0 match_look, reports on writes, set analysis, save_preset, part masks, a forgiving run_command, 66 more presets; v0.8.0 photo analysis, 134 researched presets, preset previews and search, broken built-in profiles, scaled hues and curves; v0.7.0 the terminal, Claude Code in formlit, the in-app consent token, modern list fields; v0.6.0 outside-agent consent, MCP sessions, the sidecar port; v0.3.4 the preview deadlock, keyword and stack integrity, value ranges; v0.3.3 previews read before answering, search operators; v0.3.2 originals protected, undo moves files, typed parameters, sanitized settings; v0.3.0 look tables, maker notes, DCP baselines, the frozen engine
---
@@ -255,6 +255,50 @@ The first local Linux build (v0.3.0 work) produced an engine that exited at star
When 8390 is taken the sidecar used to pass port 0 to uvicorn, so only the shell (reading the startup line) ever learned the real port. The terminal's `FORMLIT_ENGINE_URL` and the Claude Code MCP config need it inside the engine, so `free_port` binds port 0 once, reads the number, and the engine starts on that concrete port and writes it back to `FORMLIT_PORT`. The startup line still carries it, so the shell is unchanged.
+### formlit_engine.py · serve, watch_shell; app/core/startup.py; app/core/runtime.py
+- refers-to: formlit_engine.py :: serve, watch_shell, main; app/core/startup.py (new, the family's file); app/core/runtime.py (new); tests/test_startup.py (new)
+- kind: explainer
+- logged: unreleased, after v0.53.0 · 2026-11-19
+
+The family's pattern for starting and stopping cleanly beside the app, on Windows too, as FormTools 0.10.0 has it. Nothing here ran on Windows or macOS, and no frozen engine was built: "frozen" in the proofs is this entry with `sys.frozen` set.
+
+`app/core/startup.py` is FormTools's file, copied unchanged except five names at its top (`APP`, `NAMES`, `SHELL_ENV` = `FORMLIT_SHELL_PID`, `ALONE_ENV` = `FORMLIT_NO_SHELL`, `ERRORS_NAME`). `PLACES` is as it came: formlit's engine sits beside the app's program in all three install layouts (Windows install folder, `FormLit.app/Contents/MacOS`, `/usr/bin`), which `.` covers.
+
+formlit had no engine lock and no engine log file before this. Both are new and both belong to this entry only: `python -m uvicorn app.main:app` (development, the tests' `engine` fixture, the CI probe) takes no lock, starts no log file and watches nothing, as before.
+
+What `serve` does, in order: the bundled-frontend variables as before; the data folder and `Logs/formlit-engine.log` in it (`runtime.start_logging`, rotating, 1 MB, 3 kept), where a folder that cannot be made is one sentence on standard error and exit code 5; `startup.keep_errors` (an absent standard error goes to `Logs/formlit-engine-errors.log`); a frozen engine started with no `FORMLIT_SHELL_PID` opens the app beside it and returns 0, or says "formlit-engine is a part of FormLit and serves nothing on its own" and returns 4, with no lock and no port (`FORMLIT_NO_SHELL=1` lets a build check serve); `engine.lock` in the data folder, where a live engine whose shell lives refuses the new one with "formlit is already running on [folder] (engine process N)." and exit code 2, and an engine whose shell is gone is ended and replaced; the watch on the shell's process, which gives up the lock and leaves with code 0 within about two seconds of the shell ending; then the window key line and the server as before.
+
+`from app.core import config` is inside the `try`: `config` makes `Cache/kernels` under the data folder when it is imported (NUMBA_CACHE_DIR), so the folder error is raised by the import, not by `data_dir()`. Seen: with the import outside, a data folder under a plain file ended in a traceback and exit code 1.
+
+`uvicorn.run` became `uvicorn.Server(uvicorn.Config(...))` so the second `runtime.start_logging` can sit between the two: `Config` applies uvicorn's log setup, which removes every handler from the `uvicorn` loggers, and the second call puts the file handler back. Without it the log held one line. The startup line the shell reads ("Uvicorn running on http://127.0.0.1:PORT", standard error) is unchanged. The entry returns 3 when the server never started. SIGTERM gives up the lock and leaves with code 0.
+
+Only the process named in `FORMLIT_SHELL_PID` is watched. formlit watched nothing before, so an engine started without the variable (a development run of this file, or a frozen one with `FORMLIT_NO_SHELL=1`) is not tied to its parent.
+
+A lock from a released formlit does not exist (no release wrote one), so the "released engine" row of the pattern never applies: an engine left behind by 0.53.0 or older holds no lock and is not ended by the new one. It keeps port 8390, and the new engine takes a free port (`usable_port`). FormPortal's cleanup or a restart removes it.
+
+Two development runs of this file on one data folder used to both serve; the second is now refused with the sentence.
+
+Seen on Linux, with `sleep` as the stand-in shell and the real entry: second engine exit 2 with the sentence while the first kept answering `/api/health`; engine exit 0 and no lock 0.5 s after its shell was ended; a stopped (`kill -STOP`) engine whose shell was gone replaced after the five seconds, its exit 137; locks holding `not json at all`, `[1, 2]`, `{"pid": "x"}` and nothing replaced; a lock naming an unrelated `sleep` replaced and the `sleep` left running; started alone with a stand-in app in each of the three layouts exit 0, the app's mark written, no lock; with no app near exit 4 and the sentence; with the three streams closed `/api/health` answered and descriptors 0, 1 and 2 were the null device. `tests/test_startup.py` (15 tests, POSIX stand-ins) holds these.
+
+### src-tauri/src/main.rs, engine_start.rs, win_job.rs · the shell's side of the same pattern
+- refers-to: src-tauri/src/main.rs :: engine_program, forward_lines, start_engine, read_port, open_main, engine_exit_code, engine_failed, kill_backend, setup; src-tauri/src/engine_start.rs (new); src-tauri/src/win_job.rs (new, the family's file); src-tauri/Cargo.toml, Cargo.lock (windows-sys 0.61.2 under the Windows target)
+- kind: explainer
+- logged: unreleased, after v0.53.0 · 2026-11-19
+
+Logged here because `src-tauri` has no log of its own. The shell was not compiled, on any system: this machine has no WebKit libraries. What was proved is listed at the end.
+
+`win_job.rs` is FormTools's file, unchanged: `hold(&child)` puts the engine into a job object with kill-on-close, `end()` ends everything in the job. Windows closes the job when the shell ends, however it ends, and that ends the engine and what it started. `engine_start.rs` is FormTools's file with formlit's names, a two minute limit on the wait for the address (FormTools has one minute; formlit's one-file engine unpacks itself and loads more at a first start, and it had no limit at all before), and `data_folder` rewritten to mirror `app/core/config.py :: data_dir`: `FORMLIT_DATA_DIR` when it is set (a leading `~` is the home folder), else `Formlit` in the home folder, on every system. The two are kept the same by hand; the unit test `the_log_is_where_the_engine_writes_it` is where a mismatch shows.
+
+The way taken for the plugin: formlit started its engine through tauri-plugin-shell's `sidecar`, which gives no `std::process::Child`, and `win_job::hold` takes one. The one start moved to `std::process::Command` (`start_engine`, `forward_lines`, as FormTools has them), so `win_job.rs` stays unchanged. `engine_program` finds the engine where the plugin did: `formlit-engine` (`.exe` on Windows) beside the app's own program, through `tauri::utils::platform::current_exe`. The start keeps the plugin's no-console flag on Windows. Standard input is the null device now (the plugin gave a pipe that nothing wrote to). The plugin itself stays registered; nothing else used it for the engine.
+
+What changed in the start: `FORMLIT_SHELL_PID` is set to the shell's process id; every line of the engine's output goes into a `Tail`; `read_port` is FormTools's loop (the key and the address from either stream, the address wait limited, ten seconds for the key after the address, output read for as long as the engine lives); a missing engine program, a start that fails, an engine that stops, a wait that runs out and a window that does not build all end in `engine_failed`, which shows the sentence, the engine's last lines and the log's path in a dialog and only after the dialog closes the loading window, stops the engine and exits with code 1. Before, a missing or unstartable engine was a panic, a window that failed to build closed the loading window and left the app running with no window, and the one failure dialog came after the loading window was closed.
+
+`kill_backend` ends the job on Windows before the kill, and waits for the engine.
+
+Not done, on purpose: the single-instance plugin (a new crate). A second start is a second shell whose engine meets the lock and exits 2, and the person reads "FormLit could not start: another copy of its engine holds its data folder." with the first engine's own line under it.
+
+Proved here: a scratch crate that takes `engine_start.rs` and `win_job.rs` by path passed `cargo check --target x86_64-pc-windows-msvc` with no error (rustc on this machine, windows-sys 0.61.2); `cargo test` on Linux ran the module's unit tests and FormTools's loop tests over `read_port` and `engine_exit_code` cut from this `main.rs` with `awk`, behind a stand-in `tauri` module. The `Cargo.lock` line was added by hand and proved with `cargo update --workspace --offline` on a scratch copy of `Cargo.toml` and the old lock: the result is the same file. `main.rs` as a whole was read against FormTools's, not compiled: `engine_program`, `start_engine`, `open_main`, `engine_failed` and the start in `setup` have never been built.
+
---
## app/core/config.py {#core-config}
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index d175800b..42140b64 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -1,3 +1,3 @@
"""formlit engine: the catalog, the develop pipeline's reference renderer, import, export and the agent surface."""
-__version__ = "0.53.0"
+__version__ = "0.54.0"
diff --git a/backend/app/core/runtime.py b/backend/app/core/runtime.py
new file mode 100644
index 00000000..fc0175bf
--- /dev/null
+++ b/backend/app/core/runtime.py
@@ -0,0 +1,65 @@
+import json
+import logging
+import os
+from logging.handlers import RotatingFileHandler
+from pathlib import Path
+
+from app.core import startup
+
+LOG_NAME = "formlit-engine.log"
+LOG_FOLDER = "Logs"
+LOG_BYTES = 1_048_576
+LOG_KEEP = 3
+HANDLER = "formlit-file"
+LOGGERS = ("formlit", "uvicorn", "uvicorn.error", "uvicorn.access")
+FORMAT = "%(asctime)s %(levelname)s %(name)s %(message)s"
+
+AlreadyRunning = startup.Busy
+
+
+def start_logging(data: Path) -> Path:
+ folder = data / LOG_FOLDER
+ folder.mkdir(parents=True, exist_ok=True)
+ path = folder / LOG_NAME
+ for held in logging.getLogger("formlit").handlers:
+ if held.get_name() == HANDLER and getattr(held, "baseFilename", "") == os.path.abspath(path):
+ for name in LOGGERS:
+ if held not in logging.getLogger(name).handlers:
+ logging.getLogger(name).addHandler(held)
+ return path
+ stop_logging()
+ handler = RotatingFileHandler(path, maxBytes=LOG_BYTES, backupCount=LOG_KEEP, encoding="utf-8")
+ handler.setFormatter(logging.Formatter(FORMAT))
+ handler.set_name(HANDLER)
+ for name in LOGGERS:
+ logger = logging.getLogger(name)
+ logger.addHandler(handler)
+ if name == "formlit":
+ logger.setLevel(logging.INFO)
+ logging.getLogger("formlit").info("engine started, pid %s, data folder %s", os.getpid(), data)
+ return path
+
+
+def stop_logging() -> None:
+ for name in LOGGERS:
+ logger = logging.getLogger(name)
+ for handler in list(logger.handlers):
+ if handler.get_name() == HANDLER:
+ logger.removeHandler(handler)
+ handler.close()
+
+
+def claim(data: Path) -> Path:
+ lock, replaced = startup.claim(data, startup.shell_pid())
+ if replaced:
+ logging.getLogger("formlit").warning("an engine left running without its app was stopped (process %s)", replaced)
+ return lock
+
+
+def release(data: Path) -> None:
+ path = data / startup.LOCK_NAME
+ try:
+ if int(json.loads(path.read_text(encoding="utf-8")).get("pid", 0)) == os.getpid():
+ path.unlink()
+ except (OSError, ValueError, AttributeError, TypeError):
+ pass
diff --git a/backend/app/core/startup.py b/backend/app/core/startup.py
new file mode 100644
index 00000000..35794a4d
--- /dev/null
+++ b/backend/app/core/startup.py
@@ -0,0 +1,335 @@
+import json
+import os
+import signal
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+APP = "formlit"
+NAMES = ("formlit", "FormLit")
+SHELL_ENV = "FORMLIT_SHELL_PID"
+ALONE_ENV = "FORMLIT_NO_SHELL"
+LOCK_NAME = "engine.lock"
+ERRORS_NAME = "formlit-engine-errors.log"
+ERRORS_BYTES = 1_048_576
+STAND_INS = []
+PROC = "/proc"
+PLACES = ("..", ".", os.path.join("..", "..", "MacOS"), os.path.join("..", "..", "..", "bin"))
+STARTED = time.time()
+POLL = 2.0
+END_WAIT = 5.0
+STEP = 0.1
+SLACK = 3.0
+OLD_SLACK = 180.0
+FILETIME_EPOCH = 116_444_736_000_000_000
+WINDOWS = sys.platform == "win32"
+SYNCHRONIZE = 0x00100000
+QUERY_LIMITED = 0x1000
+WAIT_TIMEOUT = 0x102
+ACCESS_DENIED = 5
+NO_WINDOW = 0x08000000
+DETACHED = 0x00000008
+NEW_GROUP = 0x00000200
+FREE = "free"
+BUSY = "busy"
+LEFTOVER = "leftover"
+
+
+class Busy(RuntimeError):
+ pass
+
+
+def keep_errors(folder: Path) -> Path | None:
+ if getattr(sys.stderr, "name", None) != os.devnull:
+ return None
+ path = folder / ERRORS_NAME
+ try:
+ mode = "w" if path.stat().st_size > ERRORS_BYTES else "a"
+ except OSError:
+ mode = "a"
+ try:
+ kept = open(path, mode, encoding="utf-8", errors="replace", buffering=1)
+ except OSError:
+ return None
+ STAND_INS.append(sys.stderr)
+ sys.stderr = kept
+ return path
+
+
+def _kernel():
+ import ctypes
+
+ lib = ctypes.WinDLL("kernel32", use_last_error=True)
+ lib.OpenProcess.restype = ctypes.c_void_p
+ lib.OpenProcess.argtypes = (ctypes.c_uint32, ctypes.c_int, ctypes.c_uint32)
+ lib.WaitForSingleObject.restype = ctypes.c_uint32
+ lib.WaitForSingleObject.argtypes = (ctypes.c_void_p, ctypes.c_uint32)
+ lib.CloseHandle.restype = ctypes.c_int
+ lib.CloseHandle.argtypes = (ctypes.c_void_p,)
+ lib.GetProcessTimes.restype = ctypes.c_int
+ lib.GetProcessTimes.argtypes = (ctypes.c_void_p,) + (ctypes.POINTER(ctypes.c_uint64),) * 4
+ lib.SetDllDirectoryW.restype = ctypes.c_int
+ lib.SetDllDirectoryW.argtypes = (ctypes.c_wchar_p,)
+ return lib
+
+
+def _open_windows(pid: int, access: int):
+ import ctypes
+
+ handle = _kernel().OpenProcess(access, 0, pid)
+ if handle:
+ return handle
+ if ctypes.get_last_error() == ACCESS_DENIED:
+ raise PermissionError(pid)
+ return None
+
+
+def _alive_windows(pid: int) -> bool:
+ try:
+ handle = _open_windows(pid, SYNCHRONIZE)
+ except PermissionError:
+ return True
+ if handle is None:
+ return False
+ try:
+ return _kernel().WaitForSingleObject(handle, 0) == WAIT_TIMEOUT
+ finally:
+ _kernel().CloseHandle(handle)
+
+
+def _created_windows(pid: int) -> float:
+ import ctypes
+
+ try:
+ handle = _open_windows(pid, QUERY_LIMITED)
+ except PermissionError:
+ return 0.0
+ if handle is None:
+ return 0.0
+ try:
+ times = [ctypes.c_uint64(0) for _ in range(4)]
+ if not _kernel().GetProcessTimes(handle, *[ctypes.byref(item) for item in times]):
+ return 0.0
+ return (times[0].value - FILETIME_EPOCH) / 10_000_000
+ finally:
+ _kernel().CloseHandle(handle)
+
+
+def _end_windows(pid: int) -> None:
+ subprocess.run(
+ ["taskkill", "/PID", str(pid), "/T", "/F"],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ creationflags=NO_WINDOW,
+ timeout=END_WAIT * 2,
+ check=False,
+ )
+
+
+def _alive_posix(pid: int) -> bool:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ try:
+ with open(f"{PROC}/{pid}/stat") as stat:
+ return stat.read().rpartition(")")[2].split()[0] != "Z"
+ except (OSError, IndexError):
+ return True
+
+
+def _created_posix(pid: int) -> float:
+ try:
+ with open(f"{PROC}/{pid}/stat") as stat:
+ ticks = int(stat.read().rpartition(")")[2].split()[19])
+ with open(f"{PROC}/stat") as stat:
+ boot = int(next(line for line in stat if line.startswith("btime")).split()[1])
+ return boot + ticks / os.sysconf("SC_CLK_TCK")
+ except (OSError, IndexError, ValueError, StopIteration):
+ pass
+ found = subprocess.run(
+ ["ps", "-o", "etime=", "-p", str(pid)],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ timeout=END_WAIT,
+ check=False,
+ )
+ days, _, clock = found.stdout.decode("ascii", "replace").strip().rpartition("-")
+ parts = [int(part) for part in clock.split(":")]
+ if not 2 <= len(parts) <= 3:
+ return 0.0
+ seconds = 0
+ for part in parts:
+ seconds = seconds * 60 + part
+ return time.time() - seconds - int(days or 0) * 86400
+
+
+def alive(pid: int) -> bool:
+ if pid <= 0:
+ return False
+ return _alive_windows(pid) if WINDOWS else _alive_posix(pid)
+
+
+def created(pid: int) -> float:
+ if pid <= 0:
+ return 0.0
+ try:
+ return _created_windows(pid) if WINDOWS else _created_posix(pid)
+ except (OSError, ValueError, subprocess.SubprocessError):
+ return 0.0
+
+
+def moment(value) -> float:
+ return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0 else 0.0
+
+
+def same(pid: int, born: float) -> bool:
+ seen = created(pid)
+ return alive(pid) and (not born or (seen > 0 and abs(seen - born) <= SLACK))
+
+
+def gone_by(pid: int, seconds: float) -> bool:
+ until = time.monotonic() + seconds
+ while alive(pid):
+ if time.monotonic() >= until:
+ return False
+ time.sleep(STEP)
+ return True
+
+
+def end(pid: int) -> bool:
+ try:
+ if WINDOWS:
+ _end_windows(pid)
+ else:
+ os.kill(pid, signal.SIGTERM)
+ if gone_by(pid, END_WAIT):
+ return True
+ if not WINDOWS:
+ os.kill(pid, signal.SIGKILL)
+ except (OSError, subprocess.SubprocessError):
+ pass
+ return gone_by(pid, END_WAIT)
+
+
+def number(value) -> int:
+ return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0
+
+
+def read_lock(path: Path) -> dict:
+ try:
+ found = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return {}
+ return found if isinstance(found, dict) else {}
+
+
+def holder(lock: dict, shelled: bool) -> str:
+ pid = number(lock.get("pid"))
+ if not pid or pid == os.getpid() or not alive(pid):
+ return FREE
+ born, started, seen = moment(lock.get("born")), moment(lock.get("started")), created(pid)
+ if born:
+ if not same(pid, born):
+ return FREE
+ elif started:
+ if not seen or not -SLACK <= started - seen <= OLD_SLACK:
+ return FREE
+ else:
+ return BUSY
+ if "shell" not in lock:
+ return LEFTOVER if shelled else BUSY
+ shell = number(lock.get("shell"))
+ if not shell:
+ return BUSY
+ return BUSY if same(shell, moment(lock.get("shellBorn"))) else LEFTOVER
+
+
+def claim(data: Path, shell: int) -> tuple[Path, int]:
+ path = data / LOCK_NAME
+ lock = read_lock(path)
+ held = number(lock.get("pid"))
+ state = holder(lock, shell > 0)
+ if state == BUSY:
+ raise Busy(f"{APP} is already running on {data} (engine process {held}).")
+ if state == LEFTOVER and not end(held):
+ raise Busy(f"{APP} could not stop an engine that was left running on {data} (engine process {held}).")
+ record = {"pid": os.getpid(), "started": int(STARTED), "born": created(os.getpid()), "shell": shell, "shellBorn": created(shell)}
+ fresh = path.with_name(f"{LOCK_NAME}.{os.getpid()}")
+ fresh.write_text(json.dumps(record), encoding="utf-8")
+ os.replace(fresh, path)
+ return path, held if state == LEFTOVER else 0
+
+
+def shell_pid() -> int:
+ raw = os.environ.get(SHELL_ENV, "").strip()
+ return int(raw) if raw.isascii() and raw.isdigit() else 0
+
+
+def alone() -> bool:
+ return bool(getattr(sys, "frozen", False)) and not shell_pid() and os.environ.get(ALONE_ENV) != "1"
+
+
+def app_beside(engine: Path) -> Path | None:
+ engine = engine.resolve()
+ suffix = ".exe" if WINDOWS else ""
+ for place in PLACES:
+ for name in NAMES:
+ found = (engine.parent / place / f"{name}{suffix}").resolve()
+ if found != engine and found.is_file() and os.access(found, os.X_OK):
+ return found
+ return None
+
+
+def open_app(app: Path) -> bool:
+ env = dict(os.environ)
+ if "LD_LIBRARY_PATH_ORIG" in env:
+ env["LD_LIBRARY_PATH"] = env.pop("LD_LIBRARY_PATH_ORIG")
+ elif getattr(sys, "frozen", False):
+ env.pop("LD_LIBRARY_PATH", None)
+ try:
+ if WINDOWS:
+ _kernel().SetDllDirectoryW(None)
+ subprocess.Popen(
+ [str(app)],
+ cwd=str(app.parent),
+ env=env,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ close_fds=True,
+ creationflags=(DETACHED | NEW_GROUP) if WINDOWS else 0,
+ start_new_session=not WINDOWS,
+ )
+ except OSError:
+ return False
+ return True
+
+
+def watch(pid: int, leave) -> None:
+ direct = os.getppid() == pid
+ handle = None
+ if WINDOWS:
+ try:
+ handle = _open_windows(pid, SYNCHRONIZE)
+ except PermissionError:
+ return
+
+ def gone() -> bool:
+ if handle is not None:
+ return _kernel().WaitForSingleObject(handle, int(POLL * 1000)) != WAIT_TIMEOUT
+ time.sleep(POLL)
+ return not alive(pid) or (direct and os.getppid() != pid)
+
+ def run() -> None:
+ while not gone():
+ pass
+ leave()
+
+ threading.Thread(target=run, name=f"{APP}-shell-watch", daemon=True).start()
diff --git a/backend/formlit_engine.py b/backend/formlit_engine.py
index a1ac141a..70bb5ec0 100644
--- a/backend/formlit_engine.py
+++ b/backend/formlit_engine.py
@@ -1,6 +1,8 @@
import json
+import logging
import os
import sys
+from pathlib import Path
if sys.stdin is None:
sys.stdin = open(os.devnull, encoding="utf-8")
@@ -59,25 +61,86 @@ def free_port() -> int:
return probe.getsockname()[1]
-def main() -> int:
- if "--selfcheck" in sys.argv:
- return selfcheck()
+def watch_shell(data) -> None:
+ from app.core import runtime, startup
+
+ shell = startup.shell_pid()
+ if shell <= 1:
+ return
+
+ def leave() -> None:
+ logging.getLogger("formlit").info("the app that started this engine is gone (process %s), stopping", shell)
+ runtime.release(data)
+ os._exit(0)
+
+ startup.watch(shell, leave)
+
+
+def serve() -> int:
bundled = os.path.join(resource_dir(), "frontend_dist")
if os.path.isdir(bundled):
os.environ.setdefault("FORMLIT_DIST", bundled)
os.environ.setdefault("FORMLIT_DESKTOP", "1")
- from app.core import window_key
-
+ from app.core import runtime, startup, window_key
+
+ try:
+ from app.core import config
+
+ data = config.data_dir()
+ logs = runtime.start_logging(data).parent
+ except OSError as err:
+ print(f"formlit cannot use its data folder: {err}", file=sys.stderr)
+ return 5
+ startup.keep_errors(logs)
+ log = logging.getLogger("formlit")
+ if startup.alone():
+ beside = startup.app_beside(Path(sys.executable))
+ if beside is not None and startup.open_app(beside):
+ log.info("started without its app, so it opened %s and stopped", beside)
+ return 0
+ log.error("started without its app, and no app program was found near %s", sys.executable)
+ print("formlit-engine is a part of FormLit and serves nothing on its own. Open FormLit instead.", file=sys.stderr)
+ return 4
+ try:
+ runtime.claim(data)
+ except runtime.AlreadyRunning as err:
+ log.error("%s", err)
+ print(err, file=sys.stderr)
+ return 2
+ watch_shell(data)
if window_key.stdout_mode():
print(window_key.LINE + window_key.KEY, flush=True)
+ import signal
+
import uvicorn
from app.main import app as fastapi_app
+ def leave(_signum, _frame) -> None:
+ runtime.release(data)
+ os._exit(0)
+
+ signal.signal(signal.SIGTERM, leave)
+
port = usable_port(int(os.environ.get("FORMLIT_PORT", "0") or 0)) or free_port()
os.environ["FORMLIT_PORT"] = str(port)
- uvicorn.run(fastapi_app, host="127.0.0.1", port=port, log_level="info")
- return 0
+ server = uvicorn.Server(uvicorn.Config(fastapi_app, host="127.0.0.1", port=port, log_level="info"))
+ runtime.start_logging(data)
+ try:
+ server.run()
+ finally:
+ runtime.release(data)
+ return 0 if server.started else 3
+
+
+def main() -> int:
+ if "--selfcheck" in sys.argv:
+ return selfcheck()
+ try:
+ return serve()
+ except Exception:
+ logging.getLogger("formlit").exception("the engine stopped on an error")
+ raise
if __name__ == "__main__":
diff --git a/backend/tests/test_startup.py b/backend/tests/test_startup.py
new file mode 100644
index 00000000..b04a4628
--- /dev/null
+++ b/backend/tests/test_startup.py
@@ -0,0 +1,207 @@
+import json
+import os
+import subprocess
+import sys
+import time
+
+import pytest
+
+from conftest import BACKEND
+
+pytestmark = pytest.mark.skipif(os.name != "posix", reason="the stand-in programs are POSIX ones")
+
+FROZEN = "import sys\nsys.frozen = True\nsys.executable = {engine!r}\nsys.argv = ['formlit-engine']\nimport formlit_engine as e\nsys.exit(e.main())\n"
+SERVING = "Uvicorn running on http://127.0.0.1:"
+
+
+def stand_in():
+ return subprocess.Popen(["sleep", "120"])
+
+
+def stop(*procs):
+ for proc in procs:
+ if proc.poll() is None:
+ proc.kill()
+ proc.wait(timeout=10)
+
+
+def engine_env(data, **more):
+ env = {k: v for k, v in os.environ.items() if not k.startswith("FORMLIT_")}
+ env.update(FORMLIT_DATA_DIR=str(data), FORMLIT_PORT="0", PYTHONUNBUFFERED="1", **more)
+ return env
+
+
+def wait_for(check, seconds=90.0):
+ until = time.monotonic() + seconds
+ while time.monotonic() < until:
+ if check():
+ return True
+ time.sleep(0.1)
+ return False
+
+
+def serving(log):
+ return log.is_file() and SERVING in log.read_text()
+
+
+def record(startup, engine, shell):
+ return {"pid": engine.pid, "started": int(time.time()), "born": startup.created(engine.pid), "shell": shell.pid, "shellBorn": startup.created(shell.pid)}
+
+
+def test_a_holder_whose_shell_is_alive_is_respected(tmp_path):
+ from app.core import startup
+
+ engine, shell, mine = stand_in(), stand_in(), stand_in()
+ try:
+ (tmp_path / startup.LOCK_NAME).write_text(json.dumps(record(startup, engine, shell)))
+ with pytest.raises(startup.Busy) as refused:
+ startup.claim(tmp_path, mine.pid)
+ assert f"formlit is already running on {tmp_path} (engine process {engine.pid})" in str(refused.value)
+ assert engine.poll() is None
+ finally:
+ stop(engine, shell, mine)
+
+
+def test_a_holder_whose_shell_is_gone_is_ended_and_replaced(tmp_path):
+ from app.core import startup
+
+ engine, shell, mine = stand_in(), stand_in(), stand_in()
+ try:
+ (tmp_path / startup.LOCK_NAME).write_text(json.dumps(record(startup, engine, shell)))
+ stop(shell)
+ path, replaced = startup.claim(tmp_path, mine.pid)
+ assert replaced == engine.pid
+ assert engine.wait(timeout=10) is not None
+ now = json.loads(path.read_text())
+ assert now["pid"] == os.getpid() and now["shell"] == mine.pid and now["born"] > 0 and now["shellBorn"] > 0
+ finally:
+ stop(engine, shell, mine)
+
+
+def test_a_holder_from_an_engine_that_recorded_no_shell_is_replaced_only_by_an_engine_with_a_shell(tmp_path):
+ from app.core import startup
+
+ engine, mine = stand_in(), stand_in()
+ try:
+ (tmp_path / startup.LOCK_NAME).write_text(json.dumps({"pid": engine.pid, "started": int(time.time())}))
+ with pytest.raises(startup.Busy):
+ startup.claim(tmp_path, 0)
+ assert engine.poll() is None
+ assert startup.claim(tmp_path, mine.pid)[1] == engine.pid
+ assert engine.wait(timeout=10) is not None
+ finally:
+ stop(engine, mine)
+
+
+@pytest.mark.parametrize("text", ["not json at all", "[1, 2]", '{"pid": "x"}', ""])
+def test_a_damaged_lock_is_replaced(tmp_path, text):
+ from app.core import startup
+
+ (tmp_path / startup.LOCK_NAME).write_text(text)
+ path, replaced = startup.claim(tmp_path, 0)
+ assert replaced == 0
+ assert json.loads(path.read_text())["pid"] == os.getpid()
+
+
+def test_a_lock_that_names_a_process_which_is_not_the_engine_is_replaced_and_the_process_is_left_alone(tmp_path):
+ from app.core import startup
+
+ other, mine = stand_in(), stand_in()
+ try:
+ for held in ({"pid": other.pid, "started": int(time.time()) - 86400}, {"pid": other.pid, "started": 5, "born": 12345.5, "shell": 999999, "shellBorn": 5.0}):
+ (tmp_path / startup.LOCK_NAME).write_text(json.dumps(held))
+ assert startup.claim(tmp_path, mine.pid)[1] == 0
+ assert other.poll() is None
+ (tmp_path / startup.LOCK_NAME).write_text(json.dumps({"pid": other.pid}))
+ with pytest.raises(startup.Busy):
+ startup.claim(tmp_path, mine.pid)
+ assert other.poll() is None
+ finally:
+ stop(other, mine)
+
+
+def test_the_two_ways_of_reading_a_start_time_agree(monkeypatch):
+ from app.core import startup
+
+ first = startup.created(os.getpid())
+ monkeypatch.setattr(startup, "PROC", "/nonexistent")
+ second = startup.created(os.getpid())
+ assert first > 0 and abs(first - second) <= startup.SLACK
+ assert startup.created(4_000_000) == 0.0
+
+
+def test_the_engine_serves_and_logs_with_its_three_streams_closed(tmp_path):
+ proc = subprocess.Popen(["sh", "-c", 'exec "$0" formlit_engine.py <&- >&- 2>&-', sys.executable], cwd=BACKEND, env=engine_env(tmp_path))
+ log = tmp_path / "Logs" / "formlit-engine.log"
+ try:
+ assert wait_for(lambda: serving(log))
+ assert log.read_text().splitlines()[0].endswith(f"engine started, pid {proc.pid}, data folder {tmp_path}")
+ assert (tmp_path / "Logs" / "formlit-engine-errors.log").is_file()
+ assert json.loads((tmp_path / "engine.lock").read_text())["pid"] == proc.pid
+ finally:
+ proc.terminate()
+ proc.wait(timeout=10)
+
+
+def test_a_second_engine_on_the_same_folder_is_refused_with_the_sentence(tmp_path):
+ shell, other = stand_in(), stand_in()
+ log = tmp_path / "Logs" / "formlit-engine.log"
+ first = subprocess.Popen([sys.executable, "formlit_engine.py"], cwd=BACKEND, env=engine_env(tmp_path, FORMLIT_SHELL_PID=str(shell.pid)), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ try:
+ assert wait_for(lambda: serving(log))
+ second = subprocess.run([sys.executable, "formlit_engine.py"], cwd=BACKEND, env=engine_env(tmp_path, FORMLIT_SHELL_PID=str(other.pid)), capture_output=True, text=True, timeout=60)
+ assert second.returncode == 2
+ assert f"formlit is already running on {tmp_path} (engine process {first.pid})." in second.stderr
+ assert first.poll() is None
+ assert "is already running on" in log.read_text()
+ finally:
+ stop(shell, other, first)
+
+
+def test_the_engine_stops_when_the_shell_it_was_given_ends(tmp_path):
+ shell = stand_in()
+ log = tmp_path / "Logs" / "formlit-engine.log"
+ proc = subprocess.Popen([sys.executable, "formlit_engine.py"], cwd=BACKEND, env=engine_env(tmp_path, FORMLIT_SHELL_PID=str(shell.pid)), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ try:
+ assert wait_for(lambda: serving(log))
+ assert json.loads((tmp_path / "engine.lock").read_text())["shell"] == shell.pid
+ stop(shell)
+ assert proc.wait(timeout=10) == 0
+ assert not (tmp_path / "engine.lock").exists()
+ finally:
+ stop(shell, proc)
+
+
+def test_a_frozen_engine_started_alone_opens_the_app_beside_it_and_serves_nothing(tmp_path):
+ install, data, mark = tmp_path / "install", tmp_path / "data", tmp_path / "opened"
+ install.mkdir()
+ data.mkdir()
+ app = install / "formlit"
+ app.write_text(f'#!/bin/sh\nprintf "%s" "$(pwd)" > "{mark}"\n')
+ app.chmod(0o755)
+ code = FROZEN.format(engine=str(install / "formlit-engine"))
+ done = subprocess.run([sys.executable, "-c", code], cwd=BACKEND, env=engine_env(data), capture_output=True, text=True, timeout=60)
+ assert done.returncode == 0, done.stderr
+ assert wait_for(mark.is_file, 10)
+ assert mark.read_text() == str(install.resolve())
+ assert not (data / "engine.lock").exists()
+ assert "started without its app" in (data / "Logs" / "formlit-engine.log").read_text()
+
+
+def test_a_frozen_engine_started_alone_with_no_app_near_it_says_so_and_serves_nothing(tmp_path):
+ data = tmp_path / "data"
+ data.mkdir()
+ code = FROZEN.format(engine=str(tmp_path / "engine" / "formlit-engine"))
+ done = subprocess.run([sys.executable, "-c", code], cwd=BACKEND, env=engine_env(data), capture_output=True, text=True, timeout=60)
+ assert done.returncode == 4
+ assert "serves nothing on its own" in done.stderr
+ assert not (data / "engine.lock").exists()
+
+
+def test_a_data_folder_that_cannot_be_made_is_one_sentence_and_exit_code_5(tmp_path):
+ blocker = tmp_path / "a-file"
+ blocker.write_text("")
+ done = subprocess.run([sys.executable, "formlit_engine.py"], cwd=BACKEND, env=engine_env(blocker / "data"), capture_output=True, text=True, timeout=60)
+ assert done.returncode == 5
+ assert done.stderr.strip().startswith("formlit cannot use its data folder:")
+ assert len(done.stderr.strip().splitlines()) == 1
diff --git a/demo/HASHOUT_LOG.md b/demo/HASHOUT_LOG.md
index 79125938..c73aafe4 100644
--- a/demo/HASHOUT_LOG.md
+++ b/demo/HASHOUT_LOG.md
@@ -2,7 +2,7 @@
Rationale, decisions and removed or never-written comments for the offline demo. Source files stay comment-free.
-Current build version: v0.53.0
+Current build version: v0.54.0
## Why a TypeScript port of the pipeline
diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md
index c0726ec6..db725b06 100644
--- a/frontend/HASHOUT_LOG.md
+++ b/frontend/HASHOUT_LOG.md
@@ -2,7 +2,7 @@
Living log of all comment content, explainers, rationale, TODOs and removed code for the interface. Source files stay comment-free (vendored formvis files keep their upstream headers); everything else they would have said lives here, indexed. Read this first, then edit code surgically.
-Current build version: v0.53.0
+Current build version: v0.54.0
Last updated: 2026-11-17 · unreleased: Alt-held Sharpening views, Install Now for missing AI models (recommended or small and fast) and the learned denoiser, Update Lens Profiles with the database in use, removable Windows drives in Import, the new strings in 25 languages (keys17) (#review-gaps); camera roots in Import from feat/camera-import-profiles (#camera-import). Before: 2026-11-11 · v0.51.3 returning to the open photo in Develop cancels a switch still in progress (#v0-51-3). Before: 2026-11-10 · v0.51.2 the dev proxy follows FORMLIT_PORT; only the latest Develop photo switch takes effect; Cmd-click to deselect keeps the active photo; an emptied viewer shows the same photo again; the second window's slideshow timer stops when the mode changes; the desktop second window loads from the engine's origin; Develop tools and AI masks drop an answer for a photo that is no longer open (#v0-51-2). Before: 2026-11-10 · v0.51.1 no interface changes (the lockfile's root version field read 0.49.1 and now follows package.json; version string only). Before: 2026-11-09 · v0.51.0 the three demos open inside the app: Demos on the empty library, Help > Demos... and one Help item per demo, strings in 25 languages (#in-app-demos). Before: 2026-11-08 · v0.50.1 the desktop shell's objc2 and objc2-app-kit moved under `[target.'cfg(target_os = "macos")'.dependencies]` in src-tauri/Cargo.toml (FormVis's table): objc2 stops the build with a compile_error off Apple platforms, which failed the 0.50.0 Windows and Linux builds; every use in reveal.rs was already behind cfg(target_os = "macos") with a no-op twin, Cargo.lock needed no change, and cargo check passes on Linux here. Before: 2026-11-07 · v0.50.0 the extension host (host-bridge.ts vendored, extensions.ts, the Extensions menu and page, consent before the frame); v0.49.3 no changes to frontend/src beyond the version string (the demos in demo/ and demos/ import its modules and keep their own logs); v0.49.2 the splash page, the reveal handshake in dom.ts revealApp and the shell's splash window match formvis; v0.49.1 no changes to frontend/src beyond the version string (the demo's media pass is in demo/); v0.49.0 no changes to frontend/src beyond the version string (the offline demo in demo/ imports its modules and keeps its own log); 2026-11-05 · v0.48.0 no frontend changes (version string only); v0.47.9 no frontend changes (version string only); 2026-11-04 · v0.47.8 no frontend changes (version string only); v0.47.7 no frontend changes (README in the Form family template, Mackin's #6, merged with main); v0.47.6 the title bar and splash screen show the unified app icon (favicon.png); 2026-11-03 · v0.47.5 the About names NodeAgentc, Inc. and links the licence; 2026-10-31 · v0.47.4 no frontend changes (version string only); 2026-10-30 · v0.47.3 no frontend changes (version string only); 2026-10-26 · v0.47.2 the splash caption no longer shifts the mark (FB-110), the left Library panels reserve their empty and fixed rows (FB-111); 2026-10-24 · v0.46.6 About box credit "by nodemode.ai" (ui/about-dialog.ts: a third line in the intro's template, after the description so `q(intro, '.fl-about-line')` still finds the description first; translate="no", the owner's domain is never translated; built with the dialog, so nothing moves when it opens); v0.46.2 About box with Licences and notices (DNG notice), Intelligent Previews and Adaptable preset groups; v0.46.1 no window changes (releases move to formcompiler, version string only); v0.46.0 the app icon redrawn as a lens with iris and bokeh, in the mark, favicon and splash; v0.45.3 no window changes; v0.45.2 no window changes; v0.45.1 no window changes; v0.45.0 Depth Range pick by click, in 25 languages; v0.44.0 Keep Lines, Edge Snap, both in 25 languages, Remove-only rows hidden in Heal and Clone; v0.43.0 Show Control Maps, Same Surface, preset descriptions in all 25 languages; v0.42.2 preset names in all 25 languages, descriptions in 19; v0.42.1 preset names in 16 languages, descriptions in 7; v0.42.0 Export Group, zip import, Edge Range, Same Depth; v0.41.1 thumbnails sized before load, last cold-load shift gone; v0.41.0 no window changes; v0.40.0 Check My Style, reviewers' catalog, new strings in 25 languages; v0.39.0 PDF/X-1a option, Enhance-finish shift fixed to one resize, Develop terminology in 22 languages; v0.38.0 window exposure, SFTP, Sample from, Book Colour, terminology fixes in 12 languages; v0.37.0 People list and toast shifts fixed, plural forms in 25 languages, Send by FTP, Most picks; v0.36.0 Apply My Style, Largest spot, Shows rule, toasts stack on top, v0.36.0 strings in 25 languages; v0.35.1 no window changes; v0.35.0 the window in 26 languages, Language in Preferences, book printers; v0.34.1 translation catalogs for 25 languages (not wired yet); v0.34.0 Remove shadows option, Refresh fixed, Variations row shift fixed; v0.33.0 Flash and Window Blend in the Photo menu; v0.32.0 Retouch Skin in the Photo menu; v0.31.0 Describe filter, Relevance sort, Find Similar Photos; v0.30.2 no window changes; v0.30.1 no window changes; v0.30.0 proofing commands, client comments; v0.29.0 Astro Stack in the Photo menu; v0.28.0 Session panel and session commands; v0.27.0 Enhance names its denoiser; v0.26.3 Edit Edge Points, pending mask entry, Develop photo switch without shift; v0.26.2 no window changes; v0.26.1 Objects mask by click, two shifts logged; v0.26.0 Skin Tone and picker, picker drawer and slider thumb shifts fixed; v0.25.0 Focus Stack in the Photo menu; v0.24.0 the Layers panel and the layer editing target; v0.23.0 mask edge sliders, the Refine Edge Brush; v0.22.0 Code Replacements and Required Fields, the Metadata panel refresh fixed; v0.21.0 the Cull view, the Keywording suggestion shift fixed; v0.20.0 filmstrip collapse and top or bottom, hidden-row fix; v0.19.0 panel drag fix, chat Markdown, token meter and bridge, filmstrip resize, module show and hide; v0.18.0 workspaces, panel hide, reorder and solo, AI icons; v0.17.0 chat photo strips; v0.16.0 chat selection notes; v0.15.0 the Chat tab in the dock; v0.14.0 Claude Code in formlit section in Preferences; v0.13.0 the reference follows its edits, identity in Preferences; v0.12.0 Reference View, template lists in the import and rename dialogs; v0.11.0 template commands, keyword sets from the engine, export preset groups; v0.10.0 Refine Photos in the Library menu; v0.7.0 the terminal dock, Claude Code and the Ask line; v0.6.0 the AI agent access prompt and the Preferences AI agents section; v0.3.3 buttons follow state, shared shortcuts by module, panel header tools, toolbars that fit; v0.3.1 relative white balance; v0.3.0 view geometry, Navigator, dev font preloads
---
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 6b2ebf77..a36e1078 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "formlit",
- "version": "0.53.0",
+ "version": "0.54.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "formlit",
- "version": "0.53.0",
+ "version": "0.54.0",
"license": "Apache-2.0",
"dependencies": {
"@fontsource/inter": "5.3.0",
diff --git a/frontend/package.json b/frontend/package.json
index ac4dc58e..a85a9202 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,7 +1,7 @@
{
"name": "formlit",
"private": true,
- "version": "0.53.0",
+ "version": "0.54.0",
"description": "formlit · photo library and raw developer in the form family",
"license": "Apache-2.0",
"type": "module",
diff --git a/frontend/src/version.ts b/frontend/src/version.ts
index 8ced6d18..7da0b727 100644
--- a/frontend/src/version.ts
+++ b/frontend/src/version.ts
@@ -1 +1 @@
-export const VERSION = '0.53.0';
+export const VERSION = '0.54.0';
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 3a856541..e9c537bf 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -893,7 +893,7 @@ dependencies = [
[[package]]
name = "formlit"
-version = "0.53.0"
+version = "0.54.0"
dependencies = [
"objc2",
"objc2-app-kit",
@@ -905,6 +905,7 @@ dependencies = [
"tauri-plugin-dialog",
"tauri-plugin-shell",
"tauri-plugin-updater",
+ "windows-sys 0.61.2",
]
[[package]]
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 43e25de4..b958546b 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "formlit"
-version = "0.53.0"
+version = "0.54.0"
description = "formlit desktop shell"
authors = ["NodeAgentc, Inc."]
license = "Apache-2.0"
@@ -23,6 +23,9 @@ serde = { version = "1", features = ["derive"] }
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWindow", "NSView", "NSResponder", "objc2-core-foundation", "NSColor"] }
+[target.'cfg(target_os = "windows")'.dependencies]
+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_System_JobObjects", "Win32_System_Threading"] }
+
[profile.release]
codegen-units = 1
lto = true
diff --git a/src-tauri/src/engine_start.rs b/src-tauri/src/engine_start.rs
new file mode 100644
index 00000000..60a58d75
--- /dev/null
+++ b/src-tauri/src/engine_start.rs
@@ -0,0 +1,179 @@
+use std::collections::VecDeque;
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+pub const APP: &str = "FormLit";
+pub const SHELL_ENV: &str = "FORMLIT_SHELL_PID";
+pub const ADDRESS_WAIT: Duration = Duration::from_secs(120);
+pub const KEY_WAIT: Duration = Duration::from_secs(10);
+pub const EXIT_WAIT: Duration = Duration::from_secs(1);
+pub const EXIT_STEP: Duration = Duration::from_millis(50);
+pub const BUSY_CODE: i32 = 2;
+const DATA_NAME: &str = "Formlit";
+const DATA_ENV: &str = "FORMLIT_DATA_DIR";
+const LOG_NAME: &str = "formlit-engine.log";
+const KEY_MARK: &str = "window-key";
+const TAIL_LINES: usize = 12;
+const LINE_CHARS: usize = 300;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Wait {
+ Address,
+ Key,
+}
+
+impl Wait {
+ pub fn limit(self) -> Duration {
+ match self {
+ Wait::Address => ADDRESS_WAIT,
+ Wait::Key => KEY_WAIT,
+ }
+ }
+
+ pub fn what(self) -> &'static str {
+ match self {
+ Wait::Address => "its engine to say which address it serves on",
+ Wait::Key => "its engine to hand over the key for the window",
+ }
+ }
+}
+
+#[derive(Debug, PartialEq)]
+pub enum Failure {
+ Missing,
+ NotStarted(String),
+ Stopped(Option