Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<stem>.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.
13 changes: 13 additions & 0 deletions backend/app/core/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
57 changes: 54 additions & 3 deletions backend/app/engine/agent_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -359,13 +359,64 @@ 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_REFUSED = re.compile(r'[&|<>^()!%"\x00-\x1f\x7f]')


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 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


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)]
Expand Down
14 changes: 7 additions & 7 deletions backend/app/engine/cmd_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
12 changes: 10 additions & 2 deletions backend/app/output/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions backend/app/services/catalog_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand All @@ -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)
Expand Down
15 changes: 8 additions & 7 deletions backend/app/services/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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()


Expand Down Expand Up @@ -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}
Expand All @@ -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"],
Expand Down
90 changes: 86 additions & 4 deletions backend/app/services/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -354,10 +379,67 @@ def build_xmp(record: dict) -> str:
'<?xpacket end="w"?>\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 ('<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>\n' + ET.tostring(new_root, encoding="unicode") + '\n<?xpacket end="w"?>\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

Expand Down
22 changes: 22 additions & 0 deletions backend/app/services/xmpembed.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading