From dd2ef0d536833380c4e1d5800a3cd183ec311f65 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:18:48 -0500 Subject: [PATCH 1/6] fix: escape preset and group names before showing them in menus --- frontend/src/modules/library/painter.ts | 4 ++-- frontend/src/ui/dropdown.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/frontend/src/modules/library/painter.ts b/frontend/src/modules/library/painter.ts index e921c902..14001a45 100644 --- a/frontend/src/modules/library/painter.ts +++ b/frontend/src/modules/library/painter.ts @@ -1,5 +1,5 @@ import type { Ctx } from '../../app'; -import { el, q, setClass, setHidden } from '../../ui/dom'; +import { el, escapeHtml, q, setClass, setHidden } from '../../ui/dom'; import { icon } from '../../ui/icons'; import { toast } from '../../ui/toast'; @@ -46,7 +46,7 @@ export class Painter { const key = `${k}|${opts.length}`; if (this.value.dataset.key !== key) { this.value.dataset.key = key; - this.value.innerHTML = opts.map(([v, l]) => ``).join(''); + this.value.innerHTML = opts.map(([v, l]) => ``).join(''); } } diff --git a/frontend/src/ui/dropdown.ts b/frontend/src/ui/dropdown.ts index 4304891b..813856b8 100644 --- a/frontend/src/ui/dropdown.ts +++ b/frontend/src/ui/dropdown.ts @@ -35,7 +35,7 @@ export function enhanceSelect(select: HTMLSelectElement, opts: { search?: string const group = node instanceof HTMLOptGroupElement ? node : null, options = group ? Array.from(group.children) as HTMLOptionElement[] : [node as HTMLOptionElement]; const shown = options.filter((o) => !q || (o.textContent ?? '').toLowerCase().includes(q)); if (!shown.length) continue; - if (group && !q) list.appendChild(el(`
${group.label}
`)); + if (group && !q) { const head = el(`
`); setText(head, group.label); list.appendChild(head); } for (const o of shown) { const item = el(``); setText(item.querySelector('span') as HTMLElement, o.textContent ?? ''); From 5330743c7d46f96e1ec27f9a60bd627196d0c0a3 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:18:58 -0500 Subject: [PATCH 2/6] fix: let the stdio MCP bridge follow the engine to the port it chose The engine notes its port in its lock file; the bridge reads it there and falls back to 8390 when there is none. --- backend/app/core/runtime.py | 13 ++++++++ backend/formlit_engine.py | 1 + backend/tests/test_mcp_bridge_port.py | 43 +++++++++++++++++++++++++++ setup/mcp_stdio.py | 25 +++++++++++++--- 4 files changed, 78 insertions(+), 4 deletions(-) create mode 100644 backend/tests/test_mcp_bridge_port.py diff --git a/backend/app/core/runtime.py b/backend/app/core/runtime.py index fc0175bf..da316fe3 100644 --- a/backend/app/core/runtime.py +++ b/backend/app/core/runtime.py @@ -56,6 +56,19 @@ def claim(data: Path) -> Path: return lock +def note_port(data: Path, port: int) -> None: + path = data / startup.LOCK_NAME + try: + record = json.loads(path.read_text(encoding="utf-8")) + if int(record.get("pid", 0)) != os.getpid(): + return + fresh = path.with_name(f"{startup.LOCK_NAME}.{os.getpid()}") + fresh.write_text(json.dumps({**record, "port": int(port)}), encoding="utf-8") + os.replace(fresh, path) + except (OSError, ValueError, AttributeError, TypeError): + return + + def release(data: Path) -> None: path = data / startup.LOCK_NAME try: diff --git a/backend/formlit_engine.py b/backend/formlit_engine.py index 70bb5ec0..8e29d7b6 100644 --- a/backend/formlit_engine.py +++ b/backend/formlit_engine.py @@ -124,6 +124,7 @@ def leave(_signum, _frame) -> None: port = usable_port(int(os.environ.get("FORMLIT_PORT", "0") or 0)) or free_port() os.environ["FORMLIT_PORT"] = str(port) + runtime.note_port(data, port) server = uvicorn.Server(uvicorn.Config(fastapi_app, host="127.0.0.1", port=port, log_level="info")) runtime.start_logging(data) try: diff --git a/backend/tests/test_mcp_bridge_port.py b/backend/tests/test_mcp_bridge_port.py new file mode 100644 index 00000000..72181fe0 --- /dev/null +++ b/backend/tests/test_mcp_bridge_port.py @@ -0,0 +1,43 @@ +"""The stdio MCP bridge reaches the engine on the port the engine chose, also when 8390 was taken and it moved.""" +import importlib.util +import json +import os + +from conftest import REPO + + +def bridge(): + spec = importlib.util.spec_from_file_location("formlit_mcp_stdio", REPO / "setup" / "mcp_stdio.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_the_engine_records_its_port_in_its_lock(tmp_path): + from app.core import runtime, startup + + (tmp_path / startup.LOCK_NAME).write_text(json.dumps({"pid": os.getpid(), "started": 1}), encoding="utf-8") + runtime.note_port(tmp_path, 53122) + record = json.loads((tmp_path / startup.LOCK_NAME).read_text(encoding="utf-8")) + assert record == {"pid": os.getpid(), "started": 1, "port": 53122} + + +def test_the_engine_leaves_another_engines_lock_alone(tmp_path): + from app.core import runtime, startup + + (tmp_path / startup.LOCK_NAME).write_text(json.dumps({"pid": os.getpid() + 1}), encoding="utf-8") + runtime.note_port(tmp_path, 53122) + assert "port" not in json.loads((tmp_path / startup.LOCK_NAME).read_text(encoding="utf-8")) + + +def test_the_bridge_follows_the_port_in_the_lock(tmp_path, monkeypatch): + monkeypatch.delenv("FORMLIT_MCP_URL", raising=False) + monkeypatch.setenv("FORMLIT_DATA_DIR", str(tmp_path)) + mod = bridge() + assert mod.engine_url() == "http://127.0.0.1:8390/mcp" + (tmp_path / "engine.lock").write_text(json.dumps({"pid": 1, "port": 53122}), encoding="utf-8") + assert mod.engine_url() == "http://127.0.0.1:53122/mcp" + (tmp_path / "engine.lock").write_text(json.dumps({"pid": 1, "port": 99999}), encoding="utf-8") + assert mod.engine_url() == "http://127.0.0.1:8390/mcp" + monkeypatch.setenv("FORMLIT_MCP_URL", "http://127.0.0.1:1234/mcp") + assert mod.engine_url() == "http://127.0.0.1:1234/mcp" diff --git a/setup/mcp_stdio.py b/setup/mcp_stdio.py index 4a75ba48..363635a0 100755 --- a/setup/mcp_stdio.py +++ b/setup/mcp_stdio.py @@ -5,14 +5,31 @@ import urllib.error import urllib.request -URL = os.environ.get("FORMLIT_MCP_URL", "http://127.0.0.1:8390/mcp") +PORT = 8390 +LOCK_NAME = "engine.lock" ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) _started = False _agent = "" +def engine_port() -> int: + raw = os.environ.get("FORMLIT_DATA_DIR", "").strip() + data = os.path.expanduser(raw) if raw else os.path.join(os.path.expanduser("~"), "Formlit") + try: + with open(os.path.join(data, LOCK_NAME), encoding="utf-8") as f: + port = int(json.load(f).get("port", 0)) + except (OSError, ValueError, AttributeError, TypeError): + port = 0 + return port if 0 < port < 65536 else PORT + + +def engine_url() -> str: + return os.environ.get("FORMLIT_MCP_URL") or f"http://127.0.0.1:{engine_port()}/mcp" + + def forward(line: str) -> str | None: global _agent + url = engine_url() try: msg = json.loads(line) except ValueError: @@ -25,14 +42,14 @@ def forward(line: str) -> str | None: headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "MCP-Protocol-Version": version} if _agent: headers["x-formlit-agent"] = _agent - req = urllib.request.Request(URL, data=line.encode(), method="POST", headers=headers) + req = urllib.request.Request(url, data=line.encode(), method="POST", headers=headers) try: with urllib.request.urlopen(req, timeout=7200) as r: body = r.read().decode() except urllib.error.HTTPError as exc: body = exc.read().decode() or "" except (urllib.error.URLError, OSError) as exc: - print(f"[formlit mcp] the engine is not answering at {URL}: {exc}", file=sys.stderr, flush=True) + print(f"[formlit mcp] the engine is not answering at {url}: {exc}", file=sys.stderr, flush=True) if start_engine(): return forward(line) if msg.get("id") is None: @@ -60,7 +77,7 @@ def start_engine() -> bool: for _ in range(180): time.sleep(0.5) try: - with urllib.request.urlopen(URL.rsplit("/mcp", 1)[0] + "/api/health", timeout=2) as r: + with urllib.request.urlopen(engine_url().rsplit("/mcp", 1)[0] + "/api/health", timeout=2) as r: if r.status == 200: return True except (urllib.error.URLError, OSError): From 3ca7fd99cb1f23c2a658928550ecdcd60edc8445 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:29:29 -0500 Subject: [PATCH 3/6] fix: keep a raw file's sidecar and other XMP when saving metadata A JPEG, TIFF or DNG beside a raw file of the same name no longer reads, writes, renames, moves or deletes that raw file's .xmp sidecar; it keeps its metadata in the file. Import and move never replace a sidecar that is already at the destination. Saving metadata into a file or a sidecar keeps the XMP fields formlit does not write, such as motion photo, panorama and gain map data. --- backend/app/engine/cmd_library.py | 14 +-- backend/app/services/importer.py | 15 ++-- backend/app/services/metadata.py | 90 ++++++++++++++++++- backend/app/services/xmpembed.py | 22 +++++ backend/app/services/xmpwrite.py | 19 ++-- backend/tests/test_shared_sidecars.py | 125 ++++++++++++++++++++++++++ 6 files changed, 259 insertions(+), 26 deletions(-) create mode 100644 backend/tests/test_shared_sidecars.py diff --git a/backend/app/engine/cmd_library.py b/backend/app/engine/cmd_library.py index 638bba36..cafab809 100644 --- a/backend/app/engine/cmd_library.py +++ b/backend/app/engine/cmd_library.py @@ -494,8 +494,8 @@ def delete(ids: Any = None) -> dict: except OSError as exc: failed.append(f"{p.name}: {exc}") continue - side = metadata.sidecar_path(p) - if side.is_file(): + side = metadata.own_sidecar(p) + if side is not None: try: _trash(side) except OSError: @@ -565,9 +565,9 @@ def rename_photos(ids: Any = None, template: str = "{name}", custom: str = "", s continue if not src.is_file(): continue - target = rename.unique(dst) side = metadata.sidecar_path(src) - has_side = side.is_file() + has_side = metadata.own_sidecar(src) is not None + target = metadata.free_target(dst, side) if has_side else rename.unique(dst) try: src.rename(target) except OSError as exc: @@ -1325,14 +1325,14 @@ def photo_move(ids: Any = None, folder: int = 0) -> dict: if not src.is_file(): skipped.append(mid) continue - target = rename.unique(dest / src.name) + side = metadata.own_sidecar(src) + target = metadata.free_target(dest / src.name) if side is not None else rename.unique(dest / src.name) try: shutil.move(str(src), str(target)) except OSError as exc: failed.append(f"{src.name}: {exc}") continue - side = metadata.sidecar_path(src) - if side.is_file(): + if side is not None: try: shutil.move(str(side), str(metadata.sidecar_path(target))) except OSError as exc: diff --git a/backend/app/services/importer.py b/backend/app/services/importer.py index 23889717..dcf84af4 100644 --- a/backend/app/services/importer.py +++ b/backend/app/services/importer.py @@ -105,7 +105,7 @@ def _destination(src: Path, info: dict, dest_root: Path, folder_tmpl: str, renam name = (rename.expand(rename_tmpl, rec, seq, custom, custom) + src.suffix.lower()) if rename_tmpl else src.name target = dest_root / sub / name if sub else dest_root / name target.parent.mkdir(parents=True, exist_ok=True) - return rename.unique(target) + return metadata.free_target(target) if metadata.own_sidecar(src) is not None else rename.unique(target) def _transfer(src: Path, dst: Path, move: bool) -> None: @@ -115,12 +115,13 @@ def _transfer(src: Path, dst: Path, move: bool) -> None: tmp.unlink() raise OSError(f"copy of {src.name} came out short") tmp.replace(dst) - side = metadata.sidecar_path(src) - if side.is_file(): + side = metadata.own_sidecar(src) + copied = side is not None and not metadata.sidecar_path(dst).exists() + if copied: shutil.copy2(side, metadata.sidecar_path(dst)) if move: src.unlink() - if side.is_file(): + if copied: side.unlink() @@ -170,8 +171,8 @@ def import_files(paths: list[str], mode: str = "add", destination: str = "", fol converted = False if converted: final = target - side = metadata.sidecar_path(src) - if side.is_file(): + side = metadata.own_sidecar(src) + if side is not None and not metadata.sidecar_path(final).exists(): shutil.copy2(side, metadata.sidecar_path(final)) st = final.stat() info = {**info, "format": "dng", "size": st.st_size, "mtime": st.st_mtime} @@ -193,7 +194,7 @@ def import_files(paths: list[str], mode: str = "add", destination: str = "", fol from app.services import xmp_presets dev = xmp_presets.from_crs(xmp["crs"], (info.get("width") or 3) / max(1, info.get("height") or 2)) label = (xmp.get("label") or "").lower() - sidecars = ["xmp"] if metadata.sidecar_path(final).is_file() else [] + sidecars = ["xmp"] if metadata.own_sidecar(final) is not None else [] with cat.change(f"Import {final.name}", undoable=False) as ch: fid = cat.folder_id(ch, final.parent) pid = ch.insert("photos", folder_id=fid, file_name=final.name, sidecars=sidecars, kind=info["kind"], format=info["format"], diff --git a/backend/app/services/metadata.py b/backend/app/services/metadata.py index 97baeec2..dddacf93 100644 --- a/backend/app/services/metadata.py +++ b/backend/app/services/metadata.py @@ -183,6 +183,31 @@ def sidecar_path(path: Path) -> Path: return path.with_suffix(".xmp") +def owns_sidecar(path: Path) -> bool: + from app.services import decode, xmpembed + if not xmpembed.supports(path): + return True + for ext in sorted(decode.SUPPORTED - xmpembed.JPEG_EXT - xmpembed.TIFF_EXT): + for cand in (path.with_suffix(ext), path.with_suffix(ext.upper())): + if cand.is_file(): + return False + return True + + +def own_sidecar(path: Path) -> Path | None: + side = sidecar_path(path) + return side if side.is_file() and owns_sidecar(path) else None + + +def free_target(path: Path, keep: Path | None = None) -> Path: + from app.services import rename + cand, i = rename.unique(path), 1 + while sidecar_path(cand).exists() and sidecar_path(cand) != keep: + cand = rename.unique(path.with_name(f"{path.stem}-{i}{path.suffix}")) + i += 1 + return cand + + def _q(prefix: str, name: str) -> str: return f"{{{NS[prefix]}}}{name}" @@ -288,9 +313,9 @@ def parse_xmp(text: str) -> dict: def read_xmp(path: Path) -> dict: - side = sidecar_path(path) + side = own_sidecar(path) text = None - if side.is_file(): + if side is not None: try: text = side.read_text(encoding="utf-8", errors="replace") except OSError: @@ -354,10 +379,67 @@ def build_xmp(record: dict) -> str: '\n') -def write_sidecar(path: Path, record: dict) -> Path: +def _written_names() -> set[str]: + names = {_clark(t) for t in ("xmp:Rating", "xmp:Label", "xmp:MetadataDate", "xmp:CreatorTool", "xmpRights:Marked", "photoshop:DateCreated", + "dc:creator", "dc:subject", "lr:hierarchicalSubject", "Iptc4xmpCore:CreatorContactInfo")} + return names | {_clark(t) for t in (*SIMPLE.values(), *ALT.values(), *BAG.values())} + + +def _written(name: str) -> bool: + return name.startswith(("{" + NS["crs"] + "}", "{" + NS["fl"] + "}")) or name in _written_names() + + +def _register_prefixes(old: str) -> None: + import io + known = set(NS.values()) + try: + for _, (prefix, uri) in ET.iterparse(io.StringIO(old), events=("start-ns",)): + if prefix and prefix not in NS and uri not in known and not re.fullmatch(r"ns\d+", prefix): + ET.register_namespace(prefix, uri) + known.add(uri) + except (ET.ParseError, ValueError): + return + + +def merge_xmp(new: str, old: str | None) -> str: + old = (old or "").strip("\x00 \t\r\n") + if not old: + return new + try: + old_root = ET.fromstring(old) + new_root = ET.fromstring(new) + except ET.ParseError: + return new + desc = next(new_root.iter(_q("rdf", "Description")), None) + if desc is None: + return new + about = _q("rdf", "about") + attrs = {k: v for d in old_root.iter(_q("rdf", "Description")) for k, v in d.attrib.items() if k != about and not _written(k)} + kids = [c for d in old_root.iter(_q("rdf", "Description")) for c in d if not _written(c.tag)] + if not attrs and not kids: + return new + _register_prefixes(old) + present = set(desc.attrib) | {c.tag for c in desc} + for k, v in attrs.items(): + if k not in present: + desc.set(k, v) + for c in kids: + if c.tag not in present: + desc.append(c) + present.add(c.tag) + return ('\n' + ET.tostring(new_root, encoding="unicode") + '\n\n') + + +def write_sidecar(path: Path, record: dict, keep_other: bool = False) -> Path: side = sidecar_path(path) tmp = side.with_suffix(".xmp.tmp") - tmp.write_text(build_xmp(record), encoding="utf-8") + old = None + if keep_other and side.is_file(): + try: + old = side.read_text(encoding="utf-8", errors="replace") + except OSError: + old = None + tmp.write_text(merge_xmp(build_xmp(record), old), encoding="utf-8") tmp.replace(side) return side diff --git a/backend/app/services/xmpembed.py b/backend/app/services/xmpembed.py index 9797c426..369aaf52 100644 --- a/backend/app/services/xmpembed.py +++ b/backend/app/services/xmpembed.py @@ -109,6 +109,28 @@ def write_tiff(path: Path, packet: bytes) -> None: tmp.replace(path) +def read_jpeg(path: Path) -> str | None: + try: + data = path.read_bytes() + except OSError: + return None + i = 2 + while data[:2] == b"\xff\xd8" and i + 4 <= len(data) and data[i] == 0xFF and data[i + 1] not in (0xD9, 0xDA): + length = struct.unpack(">H", data[i + 2:i + 4])[0] + if data[i + 1] == 0xE1 and data[i + 4:i + 4 + len(XMP_NS)] == XMP_NS: + return data[i + 4 + len(XMP_NS):i + 2 + length].decode("utf-8", errors="replace") + i += 2 + length + return None + + +def read(path: Path) -> str | None: + if path.suffix.lower() in JPEG_EXT: + return read_jpeg(path) + if path.suffix.lower() in TIFF_EXT: + return read_tiff(path) + return None + + def write(path: Path, packet: str) -> None: raw = packet.encode("utf-8") if path.suffix.lower() in JPEG_EXT: diff --git a/backend/app/services/xmpwrite.py b/backend/app/services/xmpwrite.py index f8c536f3..48e034cb 100644 --- a/backend/app/services/xmpwrite.py +++ b/backend/app/services/xmpwrite.py @@ -35,14 +35,19 @@ def write(pid: int) -> str: return "" path, rec = got where = "" - if _settings["embed"] and xmpembed.supports(path) and not metadata.sidecar_path(path).is_file(): + owned = metadata.owns_sidecar(path) + if _settings["embed"] and xmpembed.supports(path) and (not owned or not metadata.sidecar_path(path).is_file()): try: - xmpembed.write(path, metadata.build_xmp(rec)) + xmpembed.write(path, metadata.merge_xmp(metadata.build_xmp(rec), xmpembed.read(path))) where = "file" - except (OSError, ValueError): + except (OSError, ValueError) as exc: + if not owned: + raise OSError(f"{path.name} could not take its metadata in the file ({exc}), and {metadata.sidecar_path(path).name} belongs to another photo with the same name") from exc where = "" + if not where and not owned: + raise OSError(f"{metadata.sidecar_path(path).name} belongs to another photo with the same name as {path.name}; turn on writing metadata into files to save it") if not where: - metadata.write_sidecar(path, rec) + metadata.write_sidecar(path, rec, keep_other=True) where = "sidecar" target = path if where == "file" else metadata.sidecar_path(path) st = target.stat() @@ -63,8 +68,7 @@ def check(ids: list[int] | None = None) -> dict: path = c.photo_path(pid) if path is None: continue - side = metadata.sidecar_path(path) - target = side if side.is_file() else path + target = metadata.own_sidecar(path) or path try: mtime = target.stat().st_mtime except OSError: @@ -88,8 +92,7 @@ def synced(ids: list[int]) -> None: path = c.photo_path(pid) if path is None: continue - side = metadata.sidecar_path(path) - target = side if side.is_file() else path + target = metadata.own_sidecar(path) or path try: ch.update("photos", pid, xmp_state=0, xmp_time=target.stat().st_mtime) except OSError: diff --git a/backend/tests/test_shared_sidecars.py b/backend/tests/test_shared_sidecars.py new file mode 100644 index 00000000..08965344 --- /dev/null +++ b/backend/tests/test_shared_sidecars.py @@ -0,0 +1,125 @@ +"""A raw and a JPEG with the same name share one .xmp sidecar name. Saving, deleting, renaming, moving or importing one +of them keeps the other's sidecar as it was, and saving metadata into a file keeps the XMP formlit does not write.""" +from pathlib import Path + +import pytest + +from conftest import gradient, write_jpeg + +FOREIGN = ( + '\n' + '' + '' + '' + '\n' +) +RAW_SIDECAR = '' + + +@pytest.fixture +def pair(commands, sandbox, request): + folder = sandbox / "pairs" / request.node.name + folder.mkdir(parents=True) + jpg = write_jpeg(folder / "IMG_0001.jpg", gradient()) + raw = folder / "IMG_0001.cr2" + raw.write_bytes(b"not decoded in these tests") + side = folder / "IMG_0001.xmp" + side.write_text(RAW_SIDECAR, encoding="utf-8") + res = commands("library.import", {"paths": [str(jpg)], "mode": "add", "wait": True, "skipDuplicates": False}) + assert res["ids"], res + return {"id": int(res["ids"][0]), "jpg": jpg, "raw": raw, "side": side, "folder": folder} + + +def test_saving_a_jpeg_keeps_the_raw_files_sidecar(commands, pair): + from app.services import xmpembed + + commands("photo.rate", {"ids": [pair["id"]], "rating": 4}) + res = commands("photo.saveMetadata", {"ids": [pair["id"]]}) + assert res["into"] == {"file": 1}, res + assert pair["side"].read_text(encoding="utf-8") == RAW_SIDECAR + assert 'xmp:Rating="4"' in (xmpembed.read(pair["jpg"]) or "") + + +def test_saving_a_jpeg_beside_a_raw_without_writing_into_files_is_refused(commands, pair, monkeypatch): + from app.engine.commands import CommandError + from app.services import xmpwrite + + monkeypatch.setitem(xmpwrite._settings, "embed", False) + commands("photo.rate", {"ids": [pair["id"]], "rating": 2}) + with pytest.raises(CommandError): + commands("photo.saveMetadata", {"ids": [pair["id"]]}) + assert pair["side"].read_text(encoding="utf-8") == RAW_SIDECAR + + +def test_deleting_a_jpeg_keeps_the_raw_files_sidecar(commands, pair, monkeypatch, tmp_path): + from app.engine import cmd_library + + trash = tmp_path / "trash" + trash.mkdir() + monkeypatch.setattr(cmd_library, "_trash", lambda p: Path(p).rename(trash / Path(p).name)) + commands("photo.delete", {"ids": [pair["id"]]}) + assert not pair["jpg"].exists() + assert pair["side"].read_text(encoding="utf-8") == RAW_SIDECAR + assert sorted(p.name for p in trash.iterdir()) == ["IMG_0001.jpg"] + + +def test_renaming_a_jpeg_leaves_the_raw_files_sidecar_in_place(commands, pair): + res = commands("photo.rename", {"ids": [pair["id"]], "template": "renamed"}) + assert [r["name"] for r in res["renamed"]] == ["renamed.jpg"], res + assert pair["side"].read_text(encoding="utf-8") == RAW_SIDECAR + assert not (pair["folder"] / "renamed.xmp").exists() + + +def test_a_jpeg_beside_a_raw_reads_its_own_metadata(pair): + from app.services import metadata + + assert metadata.own_sidecar(pair["jpg"]) is None + assert metadata.own_sidecar(pair["raw"]) == pair["side"] + + +def test_an_import_copy_never_replaces_a_sidecar_already_at_the_destination(tmp_path): + from app.services import importer + + src, dest = tmp_path / "card", tmp_path / "library" + src.mkdir() + dest.mkdir() + (src / "IMG_0002.cr2").write_bytes(b"raw") + (src / "IMG_0002.xmp").write_text("incoming", encoding="utf-8") + (dest / "IMG_0002.xmp").write_text("already here", encoding="utf-8") + target = importer._destination(src / "IMG_0002.cr2", {}, dest, "", "", 1, "") + assert target.name != "IMG_0002.cr2" + importer._transfer(src / "IMG_0002.cr2", target, move=False) + assert (dest / "IMG_0002.xmp").read_text(encoding="utf-8") == "already here" + assert target.with_suffix(".xmp").read_text(encoding="utf-8") == "incoming" + (dest / "IMG_0003.xmp").write_text("also here", encoding="utf-8") + importer._transfer(src / "IMG_0002.cr2", dest / "IMG_0003.cr2", move=True) + assert (dest / "IMG_0003.xmp").read_text(encoding="utf-8") == "also here" + assert (src / "IMG_0002.xmp").read_text(encoding="utf-8") == "incoming" + + +def test_saving_into_a_jpeg_keeps_the_xmp_formlit_does_not_write(commands, photo): + from app.services import metadata, xmpembed + + xmpembed.write(photo["path"], FOREIGN) + commands("photo.rate", {"ids": [photo["id"]], "rating": 5}) + res = commands("photo.saveMetadata", {"ids": [photo["id"]]}) + assert res["into"] == {"file": 1}, res + text = xmpembed.read(photo["path"]) or "" + assert 'GCamera:MotionPhoto="1"' in text + assert "Container:Directory" in text and 'Item:Semantic="MotionPhoto"' in text + assert text.count("xmp:Rating=") == 1 and 'xmp:Rating="5"' in text + assert metadata.parse_xmp(text)["rating"] == 5 + + +def test_saving_a_sidecar_keeps_the_xmp_formlit_does_not_write(tmp_path): + from app.services import metadata + + raw = tmp_path / "IMG_0004.cr2" + raw.write_bytes(b"raw") + raw.with_suffix(".xmp").write_text(FOREIGN, encoding="utf-8") + metadata.write_sidecar(raw, {"rating": 3, "label": "", "meta": {}, "keywords": []}, keep_other=True) + text = raw.with_suffix(".xmp").read_text(encoding="utf-8") + assert 'GCamera:MotionPhoto="1"' in text and text.count("xmp:Rating=") == 1 + assert metadata.parse_xmp(text)["rating"] == 3 From b454a1abe6f6f02760286a4544894b8aae6a7768 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 10:19:35 -0500 Subject: [PATCH 4/6] fix: start npm shims directly on Windows and check words given to cmd.exe A .cmd or .bat agent program is started as the node script or program its npm shim names. A file that is not such a shim still goes through cmd.exe /c, which now refuses control characters, percent signs, double quotes, special characters in unquoted words and a program path that needs quotes. The shared finder becomes 1.0.2. --- backend/app/engine/agent_lookup.py | 56 ++++++++++++++++- backend/tests/test_agent_start_windows.py | 76 +++++++++++++++++++++++ setup/agents.py | 1 + 3 files changed, 130 insertions(+), 3 deletions(-) create mode 100644 backend/tests/test_agent_start_windows.py diff --git a/backend/app/engine/agent_lookup.py b/backend/app/engine/agent_lookup.py index ea34eba1..704f5a64 100644 --- a/backend/app/engine/agent_lookup.py +++ b/backend/app/engine/agent_lookup.py @@ -26,7 +26,7 @@ from dataclasses import dataclass, field from pathlib import Path -VERSION = "1.0.1" +VERSION = "1.0.2" PROGRAMS: dict = { "claude": {"title": "Claude Code", "names": ("claude",), "setting": "claudeBin", "install": "curl -fsSL https://claude.ai/install.sh | bash", "install_windows": "irm https://claude.ai/install.ps1 | iex", @@ -359,13 +359,63 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +class CommandLineRefused(OSError): + pass + + +SHIM_TARGET = re.compile(r'"%~?dp0%?\\([^"%\r\n]+)"\s+%\*') +SCRIPT_ENDINGS = (".js", ".cjs", ".mjs") +CMD_SPECIAL = frozenset("&|<>^()!") + + +def shim_target(path: str, env: dict) -> list[str] | None: + """What an npm style .cmd shim starts, as the words to start it with directly: [node, script] or [program]. None when + the file is not such a shim or its target or node cannot be found.""" + shim = Path(path) + try: + text = shim.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + hits = SHIM_TARGET.findall(text) + if not hits: + return None + target = shim.parent.joinpath(*[part for part in re.split(r"[\\/]", hits[-1]) if part]) + if not target.is_file(): + return None + if target.suffix.lower() not in SCRIPT_ENDINGS: + return [str(target)] if target.suffix.lower() == ".exe" else None + beside = shim.parent / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH") or os.environ.get("PATH", "")) + return [node, str(target)] if node else None + + +def cmd_words(words: list[str]) -> list[str]: + """The words for cmd.exe /c, refused (CommandLineRefused) when the command interpreter would read any of them as more + than text: control characters, percent signs or double quotes anywhere, its special characters in a word that will not + be quoted, and a program path that would need quotes.""" + for i, word in enumerate(words): + quoted = word == "" or " " in word or "\t" in word + if re.search(r"[\x00-\x1f\x7f]", word) or "%" in word or '"' in word: + raise CommandLineRefused(f"{Path(words[0]).name} cannot be given this text through the command interpreter") + if (i == 0 and quoted) or (not quoted and CMD_SPECIAL & set(word)): + raise CommandLineRefused(f"{Path(words[0]).name} cannot be given this text through the command interpreter") + return words + + def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]: """How a program is started, the same for a tab, Chat and a check: through the person's login shell on macOS and Linux - (exec, so the process is the program), directly on Windows with the command interpreter in front of a .cmd or .bat.""" + (exec, so the process is the program), directly on Windows. A .cmd or .bat on Windows is started as the node script or + program its npm shim names; only a file that is not such a shim goes through the command interpreter, with its words + checked by cmd_words.""" words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words + if not words[0].lower().endswith((".cmd", ".bat")): + return words + target = shim_target(words[0], env) + if target: + return [*target, *words[1:]] + return [env.get("COMSPEC") or "cmd.exe", "/c", *cmd_words(words)] shell = login_shell(env, platform) fish = Path(shell).name == "fish" return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] diff --git a/backend/tests/test_agent_start_windows.py b/backend/tests/test_agent_start_windows.py new file mode 100644 index 00000000..ffd477dd --- /dev/null +++ b/backend/tests/test_agent_start_windows.py @@ -0,0 +1,76 @@ +"""On Windows an agent program installed as a .cmd shim is started as the node script or program the shim names, and +only a file that is not such a shim goes through the command interpreter, which never receives text it would read as +more than words.""" +import pytest + +from app.engine import agent_lookup + +NPM_SHIM = ( + "@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\n" + 'IF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n' + " SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\n" + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\agent\\cli.js" %*\r\n' +) + + +@pytest.fixture +def shim(tmp_path): + folder = tmp_path / "npm" + (folder / "node_modules" / "agent").mkdir(parents=True) + (folder / "node_modules" / "agent" / "cli.js").write_text("", encoding="utf-8") + (folder / "node.exe").write_bytes(b"") + path = folder / "agent.cmd" + path.write_text(NPM_SHIM, encoding="utf-8") + return path + + +def test_an_npm_shim_starts_its_script_with_node_and_no_command_interpreter(shim): + text = 'fix "this" & that | more 100% (now)\nnext line' + argv = agent_lookup.start_argv([str(shim), "-p", "--", text], {"COMSPEC": "cmd.exe"}, "win32") + folder = shim.parent + assert argv == [str(folder / "node.exe"), str(folder / "node_modules" / "agent" / "cli.js"), "-p", "--", text] + + +def test_a_shim_that_names_a_program_starts_that_program(tmp_path): + (tmp_path / "bin").mkdir() + (tmp_path / "bin" / "agent.exe").write_bytes(b"") + path = tmp_path / "agent.cmd" + path.write_text('@"%~dp0\\bin\\agent.exe" %*\r\n', encoding="utf-8") + assert agent_lookup.start_argv([str(path), "--version"], {}, "win32") == [str(tmp_path / "bin" / "agent.exe"), "--version"] + + +def test_a_shim_whose_target_is_missing_is_not_followed(shim): + (shim.parent / "node_modules" / "agent" / "cli.js").unlink() + assert agent_lookup.shim_target(str(shim), {}) is None + + +@pytest.fixture +def plain(tmp_path): + path = tmp_path / "agent.bat" + path.write_text("@echo off\r\nrem a launcher that is not an npm shim\r\n", encoding="utf-8") + return path + + +def test_plain_words_still_go_through_the_command_interpreter(plain): + argv = agent_lookup.start_argv([str(plain), "--version"], {"COMSPEC": "cmd.exe"}, "win32") + assert argv == ["cmd.exe", "/c", str(plain), "--version"] + assert agent_lookup.start_argv([str(plain), "-p", "--", "tidy up & sort (all) of it"], {}, "win32")[-1] == "tidy up & sort (all) of it" + + +@pytest.mark.parametrize("word", ["two\nlines", "tab\there\x00", "bell\x07", "del\x7f", "50%", "%PATH%", 'say "hi"', "a&b", "a|b", "a>b", "a Date: Sun, 29 Nov 2026 10:19:36 -0500 Subject: [PATCH 5/6] fix: keep a same-named raw file's sidecar on export and catalog copy Exporting an original or a DNG beside a raw of the same name puts the metadata in the file instead of replacing the raw file's sidecar, and copying photos into a new catalog takes a sidecar only with the photo that owns it. --- backend/HASHOUT_LOG.md | 14 ++++++++++++++ backend/app/output/export.py | 12 ++++++++++-- backend/app/services/catalog_io.py | 4 ++-- backend/tests/test_shared_sidecars.py | 23 +++++++++++++++++++++++ 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index eb67f3bf..e74052de 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2294,6 +2294,20 @@ Seen on Linux, where closing the streams (`python formlit_engine.py >&- 2>&-`) a Preferences now has a field for the Codex, Cursor and Antigravity programs beside the Claude Code one (frontend log, #prefs-four-programs), so the sentence for a program that is not found or does not start ends with "give its path in Preferences" for all four, not only for Claude Code. `otherwise` returns the clause for every kind the finder knows (`agent_lookup.PROGRAMS`) and nothing for any other. The test asserts the ending for Codex, Cursor and Antigravity as it did for Claude Code; `test_dock_contract.py` and `test_window_key.py` 43 passed. +### app/engine/agent_lookup.py at 1.0.2 · setup/agents.py · LOOKUP_HASHES +- refers-to: app/engine/agent_lookup.py :: start_argv, shim_target, cmd_words, CommandLineRefused; setup/agents.py :: LOOKUP_HASHES; tests/test_agent_start_windows.py +- kind: fix +- logged: unreleased · 2026-11-29 + +On Windows a `.cmd` or `.bat` program went through `cmd.exe /c`, which reads percent signs, double quotes, line breaks and its special characters in the words after it, so a Chat prompt or a Codex `-c` value did not arrive as written. `start_argv` now reads an npm style shim (`"%dp0%\...\cli.js" %*`) and starts the node beside it, or on PATH, with that script, or the `.exe` it names, with no command interpreter. Only a file that is not such a shim still goes through `cmd.exe /c`, and `cmd_words` refuses (`CommandLineRefused`, an `OSError`, so every caller's existing handling applies) control characters, `%` and `"` in any word, `&|<>^()!` in a word that will not be quoted, and a program path that would need quotes, since a quoted first word makes `/c` drop the first and last quote of the line. This file is the first 1.0.2; FormVis's copy of the finder needs the same file before the family copies it on; `LOOKUP_HASHES` keeps 1.0.0 and 1.0.1. + +### app/output/export.py · app/services/catalog_io.py · owns_sidecar +- refers-to: app/output/export.py :: the original and DNG formats; app/services/catalog_io.py :: _copy_file; tests/test_shared_sidecars.py +- kind: fix +- logged: unreleased · 2026-11-29 + +Exporting an original, or a DNG whose metadata cannot go into the file, wrote `.xmp` in the export folder even when a raw file of the same name there owns it. Such a file now takes its metadata in the file (or keeps what it has), and the other sidecar stays. Exporting photos into a new catalog copies a sidecar only beside the photo that owns it, so a JPEG copied without its raw no longer takes the raw's settings with it. + ## Files with no entries {#no-entries} No logged content at v0.1.0 for: `app/__init__.py`, `app/main.py`, `app/engine/events.py`, `app/engine/tasks.py`, `app/engine/query.py`, `app/engine/records.py`, `app/develop/settings.py`, `app/develop/geometry.py`, `app/develop/planes.py`, `app/develop/retouch.py`, `app/develop/colorops.py`, `app/develop/colour.py`, `app/develop/curves.py`, `app/develop/auto.py`, `app/develop/camera_look.py`, `app/develop/lensprofile.py`, `app/develop/fringe.py`, `app/develop/output.py`, `app/ai/models.py`, `app/ai/nets.py`, `app/ai/parts.py`, `app/ai/cull.py`, `app/ai/upright.py`, `app/ai/dng.py`, `app/output/icc.py`, `app/output/web.py`, `app/services/importer.py`, `app/services/metadata.py`, `app/services/xmp_presets.py`, `app/services/xmpwrite.py`, `app/services/xmpembed.py`, `app/services/rename.py`, `app/services/lensdb.py`, `app/services/watch.py`, `app/services/catalog_io.py`, and the remaining routers. diff --git a/backend/app/output/export.py b/backend/app/output/export.py index 4a738cc0..dab4b6b8 100644 --- a/backend/app/output/export.py +++ b/backend/app/output/export.py @@ -417,7 +417,14 @@ def export_one(pid: int, s: dict, seq: int, kw_filter: dict | None) -> Path | No shutil.copy2(src, dest) from app.services import metadata full = dict(meta_rec, develop=json.dumps(rec.get("develop") or {}, separators=(",", ":"))) - metadata.write_sidecar(dest, full) + if metadata.owns_sidecar(dest): + metadata.write_sidecar(dest, full) + else: + from app.services import xmpembed + try: + xmpembed.write(dest, metadata.build_xmp(full)) + except (OSError, ValueError): + pass return dest if fmt == "dng": from app.ai import dng @@ -445,7 +452,8 @@ def export_one(pid: int, s: dict, seq: int, kw_filter: dict | None) -> Path | No from app.services import xmpembed xmpembed.write(dest, metadata.build_xmp(full)) except (OSError, ValueError): - metadata.write_sidecar(dest, full) + if metadata.owns_sidecar(dest): + metadata.write_sidecar(dest, full) return dest ext = encode.FORMATS.get(fmt, encode.FORMATS["jpeg"])["ext"] dest = place(folder / f"{stem}.{ext}", existing) diff --git a/backend/app/services/catalog_io.py b/backend/app/services/catalog_io.py index 0af161b3..71e423f1 100644 --- a/backend/app/services/catalog_io.py +++ b/backend/app/services/catalog_io.py @@ -8,7 +8,7 @@ from app.engine import catalog as catalog_mod from app.engine import records from app.engine.catalog import JSON_FIELDS, Catalog, now_iso -from app.services import rename +from app.services import metadata, rename SIDECARS = (".xmp", ".XMP") @@ -18,7 +18,7 @@ def _copy_file(src: Path, dest_dir: Path) -> Path: dst = dest_dir / src.name if not dst.exists(): shutil.copy2(src, dst) - for ext in SIDECARS: + for ext in SIDECARS if metadata.owns_sidecar(src) else (): side = src.with_suffix(ext) if side.is_file() and not (dest_dir / side.name).exists(): shutil.copy2(side, dest_dir / side.name) diff --git a/backend/tests/test_shared_sidecars.py b/backend/tests/test_shared_sidecars.py index 08965344..729939f0 100644 --- a/backend/tests/test_shared_sidecars.py +++ b/backend/tests/test_shared_sidecars.py @@ -123,3 +123,26 @@ def test_saving_a_sidecar_keeps_the_xmp_formlit_does_not_write(tmp_path): text = raw.with_suffix(".xmp").read_text(encoding="utf-8") assert 'GCamera:MotionPhoto="1"' in text and text.count("xmp:Rating=") == 1 assert metadata.parse_xmp(text)["rating"] == 3 + + +def test_exporting_an_original_jpeg_beside_a_raw_keeps_the_raw_files_sidecar(commands, pair, sandbox): + from app.services import xmpembed + + out = sandbox / "out" / "pair" + out.mkdir(parents=True) + (out / "IMG_0001.cr2").write_bytes(b"exported raw") + (out / "IMG_0001.xmp").write_text(RAW_SIDECAR, encoding="utf-8") + res = commands("export.run", {"ids": [pair["id"]], "settings": {"file": {"format": "original"}, "destination": {"folder": str(out)}}, "wait": True}) + assert not res["failed"], res + assert (out / "IMG_0001.xmp").read_text(encoding="utf-8") == RAW_SIDECAR + assert 'crs:HasSettings="True"' in (xmpembed.read(out / "IMG_0001.jpg") or "") + + +def test_copying_a_jpeg_into_a_catalog_leaves_the_raw_files_sidecar_behind(pair, tmp_path): + from app.services import catalog_io + + dst = catalog_io._copy_file(pair["jpg"], tmp_path / "copied") + assert dst.is_file() + assert sorted(p.name for p in dst.parent.iterdir()) == ["IMG_0001.jpg"] + raw = catalog_io._copy_file(pair["raw"], tmp_path / "copied") + assert raw.with_suffix(".xmp").read_text(encoding="utf-8") == RAW_SIDECAR From 679fd310419ffcac86f736637e54f51d88cacdae Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:57:17 -0500 Subject: [PATCH 6/6] fix: refuse every cmd.exe special character whether or not a word has spaces A word given to cmd.exe /c is refused when it holds any of & | < > ^ ( ) ! % " or a control character, quoted or not, since a batch file reads its arguments again. The message asks for long text through standard input or a file. npm shims are still started directly as their node script or program. The recorded hash for the shared finder 1.0.2 follows. --- backend/app/engine/agent_lookup.py | 21 +++++++++++---------- backend/tests/test_agent_start_windows.py | 18 ++++++++++++++---- setup/agents.py | 2 +- 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/backend/app/engine/agent_lookup.py b/backend/app/engine/agent_lookup.py index 704f5a64..bc8117d1 100644 --- a/backend/app/engine/agent_lookup.py +++ b/backend/app/engine/agent_lookup.py @@ -365,7 +365,7 @@ class CommandLineRefused(OSError): SHIM_TARGET = re.compile(r'"%~?dp0%?\\([^"%\r\n]+)"\s+%\*') SCRIPT_ENDINGS = (".js", ".cjs", ".mjs") -CMD_SPECIAL = frozenset("&|<>^()!") +CMD_REFUSED = re.compile(r'[&|<>^()!%"\x00-\x1f\x7f]') def shim_target(path: str, env: dict) -> list[str] | None: @@ -390,15 +390,16 @@ def shim_target(path: str, env: dict) -> list[str] | None: def cmd_words(words: list[str]) -> list[str]: - """The words for cmd.exe /c, refused (CommandLineRefused) when the command interpreter would read any of them as more - than text: control characters, percent signs or double quotes anywhere, its special characters in a word that will not - be quoted, and a program path that would need quotes.""" - for i, word in enumerate(words): - quoted = word == "" or " " in word or "\t" in word - if re.search(r"[\x00-\x1f\x7f]", word) or "%" in word or '"' in word: - raise CommandLineRefused(f"{Path(words[0]).name} cannot be given this text through the command interpreter") - if (i == 0 and quoted) or (not quoted and CMD_SPECIAL & set(word)): - raise CommandLineRefused(f"{Path(words[0]).name} cannot be given this text through the command interpreter") + """The words for cmd.exe /c, refused (CommandLineRefused) when any word holds one of & | < > ^ ( ) ! % " or a control + character, quoted or not, or when the program path holds a space. Quotes do not protect a word here: a batch file + reads its arguments again.""" + name = Path(words[0]).name + if " " in words[0]: + raise CommandLineRefused(f"{name} is in a folder whose path has a space, so it cannot be started through the command interpreter") + for word in words: + if CMD_REFUSED.search(word): + raise CommandLineRefused(f"{name} cannot be given the characters & | < > ^ ( ) ! % \" or control characters through the command " + "interpreter; pass long text through standard input or a file if the program supports it") return words diff --git a/backend/tests/test_agent_start_windows.py b/backend/tests/test_agent_start_windows.py index ffd477dd..ddfa7636 100644 --- a/backend/tests/test_agent_start_windows.py +++ b/backend/tests/test_agent_start_windows.py @@ -54,13 +54,23 @@ def plain(tmp_path): def test_plain_words_still_go_through_the_command_interpreter(plain): argv = agent_lookup.start_argv([str(plain), "--version"], {"COMSPEC": "cmd.exe"}, "win32") assert argv == ["cmd.exe", "/c", str(plain), "--version"] - assert agent_lookup.start_argv([str(plain), "-p", "--", "tidy up & sort (all) of it"], {}, "win32")[-1] == "tidy up & sort (all) of it" + assert agent_lookup.start_argv([str(plain), "-p", "--", "tidy up, then sort all of it"], {}, "win32")[-1] == "tidy up, then sort all of it" -@pytest.mark.parametrize("word", ["two\nlines", "tab\there\x00", "bell\x07", "del\x7f", "50%", "%PATH%", 'say "hi"', "a&b", "a|b", "a>b", "ab", "a