Compare commits

...
Author SHA1 Message Date
Vito b3bb55f2dc chore: release 3.7.1 (#655) 2026-11-19 14:26:54 +00:00
LacklusterOpsec fa31644c4c fix(node): give prepend_text and append_text their empty default (#651)
Both inputs are optional STRINGs that the node already treats as empty
(`encode_prompt` defaults them to ""), but INPUT_TYPES left "default"
out, so `/object_info` and the v3 schema answer null for them while
category, tags and search_text answer "". PromptManagerFocused already
forces "default": "" on the same two inputs, so the plain node was the
only one without it; Focused, Split and Pair inherit the fix.

The test asserts every optional STRING of PromptManager starts empty.
2026-11-19 11:35:37 +00:00
Vito 0c023c7ec9 test(inspect): wait for the held video's revoke instead of checking once (#653) (#654)
On WebKit a replaced video that is still starting, inline or in the
viewer the selection opened, keeps its URL until it settles or 15 s
pass. The test checked the revoke once, right after the new preview
showed, so it failed when the viewer's video settled later.
2026-11-19 11:35:36 +00:00
LacklusterOpsecandVito Sansevero 9943a61619 fix(images): link WebP images to their prompts (#650)
* fix(images): link WebP and AVIF images to their prompts

ComfyUI writes the workflow and the prompt into PNG text chunks, and the
library read only those. SaveAnimatedWEBP writes the same records as EXIF
instead: `prompt:{json}` at tag 0x0110, then `workflow:{json}` and every
other `extra_pnginfo` key from 0x010F down; the AVIF writer uses that
layout. Pillow answers them only through `getexif()`, so an animated WebP
or an AVIF scanned into the library matched no prompt and stayed unlinked.

`utils/exif_text.py` answers the `png_text` shape from those tags, and
both metadata readers (the scan's `_extract_comfyui_metadata` and the
monitor's `extract_metadata`) ask it when a file has no text chunks. Only a
value shaped like a record counts, so camera EXIF stays out. PNG is
unchanged: its records are text chunks and `exif_text` answers `{}`.

The tests write real still and animated WebP, AVIF (where Pillow has it) and
JPEG files in ComfyUI's layout, and hold both readers to them.

* docs(images): AVIF is read but not yet collected (#652)

The EXIF reader handles ComfyUI's AVIF files, verified against files
written by ComfyUI's own _save_avif. No scan, monitor or gallery list
collects .avif yet, so say so and point at #652.

---------

Co-authored-by: Vito Sansevero <vito.sansevero@gmail.com>
2026-11-19 01:00:17 +00:00
Vito 1d509c885e chore: release 3.7.0 (refuse permanent delete off Linux/BSD, #644) (#645)
* fix(images): refuse permanent delete where the review does not offer it (#644)

The apply accepted mode "permanent" on every OS; only the workspace hid
the option. A direct call on Windows or macOS unlinked files although the
README says Windows can only remove images from the library. The apply now
answers 400 unless the Freedesktop trash backend is in use, before any
backup or file change. The review and the apply share one check.

The README describes the new option and its limit.

* chore: release 3.7.0
2026-11-17 22:02:44 +00:00
Vito 96ce361b82 fix(paths): a backslash inside a name works on Linux and macOS servers (#646) (#649)
* fix(paths): a backslash inside a name works on Linux and macOS servers (#646)

On POSIX a backslash is an ordinary character, and a Windows-style
filename_prefix makes a folder whose name holds one. The listing named such
a file, but the workspace and the tag, favorite, collection, delete,
thumbnail and folder-filter routes refused it or split the name at the
backslash. Separators are now the server's own: / always, \ only on
Windows. Windows keeps every refusal it had.

The listing marks a path holding a backslash with path_style "posix", and
the workspace accepts the backslash only with that mark. Scan rows,
duplicate keys and the folder tree no longer turn \ into /, so a\b.png and
a/b.png stay two files.

* fix(paths): Needs review and tagging take a backslash name too (#646)

Needs review built its own image entries without the POSIX mark, so Open
and Info still failed there for a name holding a backslash (Codex P2). The
review target now carries path_style like the Images listing, and imageOf
passes it on.

The capture store, which tagging and review read through, refused every
backslash; it now refuses one only on Windows. Before this, such a file
could not be tagged and never reached Needs review.

* fix(tests): shared-listing tests wait for the workspace cache build before teardown

A read that stores a listing starts the workspace cache build on a worker
thread, and cancelling its task at cleanup does not stop the thread. A test
that ended on that read could reach teardown while the thread opened a
database connection, and the leak check failed (queue run 44164234834,
py3.14). Teardown now stops new builds and waits for the running one. On
one busy CPU the test failed 8 of 60 runs before and 0 of 60 after.

* fix(tests): the pool-reuse test makes its first job run on both threads

ThreadPoolExecutor starts threads lazily and skips a new one while another
is idle. The first job's tiny tasks could all run on worker 0 and leave
worker 1 to start in the second job, so second <= first failed although the
pool was reused (queue run 44169912829: first {worker_0}, second
{worker_1}). A two-party barrier now makes the first job run on both.
2026-11-17 21:08:41 +00:00
47 changed files with 765 additions and 63 deletions
+2 -1
View File
@@ -103,7 +103,7 @@ Pick an open ComfyUI window and a node, then review the exact before and after.
### Deletes you can review
Choose what happens to the files before anything is removed: remove the image from the library and leave the file on disk, or on Linux and macOS also move it to the system trash. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
Choose what happens to the files before anything is removed: remove the image from the library and leave the file on disk, or on Linux and macOS also move it to the system trash. On a Linux or BSD server you can also delete the files permanently, for headless servers where a trash only fills up the disk; those files can't be recovered. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
![Delete dialog offering to remove from the library only or move files to the trash](assets/readme/delete-review.webp)
@@ -230,6 +230,7 @@ The documentation for those pages is in [README-legacy.md](README-legacy.md).
## Known limits
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists why for each file.
- **Permanent delete is Linux and BSD only,** and can't be undone. The safety backup brings back the library records, not the files.
- **Show in folder** opens the file manager on the machine running ComfyUI, not necessarily the one with your browser.
- **Returned images** get their prompt links back, but not their tags, categories, collections or favorites.
- **Inspect a file** doesn't add the file to your library.
+13
View File
@@ -491,6 +491,19 @@ differ are files whose pixel data is undecodable or cut short: legacy found
nothing, the walk keeps the text before the pixels. Animated PNGs still use
`.text`.
WebP, AVIF and JPEG keep the same records in EXIF, not in text chunks.
ComfyUI's `SaveAnimatedWEBP` writes `prompt:{json}` to EXIF tag 0x0110, then
`workflow:{json}` and every other `extra_pnginfo` key to 0x010F and down; the
AVIF writer uses that layout. `utils/exif_text.py` answers the `png_text` shape
through Pillow's `getexif()`, and both metadata readers fall back to it when a
file has no text chunks. Only a value shaped like a record counts (a key, a
colon, then a JSON object, array or string), so camera EXIF stays out.
`tests/test_exif_text.py` writes real still and animated WebP files, AVIF (where
Pillow has it) and JPEG in that layout; `tests/test_metadata_extraction.py` and
`tests/test_api_core.py` hold the two readers to it. No scan, monitor or
gallery list collects `.avif` yet, so AVIF files are read correctly but never
reach the readers; #652 tracks AVIF as a media type.
Image work runs on PromptManager's own threads (#523). glibc keeps each thread's
malloc arena at its high-water mark, so image buffers spread over the default
executor's threads stay resident. Interactive image work (view previews behind their
+2 -1
View File
@@ -1049,7 +1049,8 @@ class PromptDatabase(
if include_ancestors:
ancestors = set()
for folder in folders:
parts = folder.replace("\\", "/").split("/")
# #646: ``folder`` already uses ``/``; on POSIX ``\\`` is a name.
parts = folder.split("/")
for i in range(1, len(parts)):
ancestors.add("/".join(parts[:i]))
folders.update(ancestors)
+4 -2
View File
@@ -99,19 +99,21 @@ class PromptManager(PromptManagerBase, ComfyNodeABC):
"prepend_text": (
IO.STRING,
{
"default": "",
"tooltip": (
"Text to prepend to the main prompt (connected STRING "
"nodes will be added before the main text)"
)
),
},
),
"append_text": (
IO.STRING,
{
"default": "",
"tooltip": (
"Text to append to the main prompt (connected STRING "
"nodes will be added after the main text)"
)
),
},
),
"save_to_library": SAVE_TO_LIBRARY_INPUT,
+7 -3
View File
@@ -89,6 +89,7 @@ from .source_rescope import SourceRescopeMixin
try:
from ...database.operations import PromptDatabase
from ...utils.exif_text import exif_text
from ...utils.logging_config import get_logger
from ...utils.native_memory import release_free_memory
from ...utils.png_text import png_text
@@ -100,6 +101,7 @@ except ImportError:
0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)
from database.operations import PromptDatabase
from utils.exif_text import exif_text
from utils.logging_config import get_logger
from utils.native_memory import release_free_memory
from utils.png_text import png_text
@@ -1018,9 +1020,11 @@ class PromptManagerAPI(
return []
def _extract_comfyui_metadata(self, image_path):
"""Embedded ComfyUI metadata of an image (PNG text chunks) or a video.
"""Embedded ComfyUI metadata of an image (PNG text, EXIF) or a video.
PNG text is read without decoding the pixels (``utils.png_text``, #523).
PNG text is read without decoding the pixels (``utils.png_text``, #523);
WebP, AVIF and JPEG keep the same records as EXIF strings, read through
``utils.exif_text``.
Videos go through ffprobe (see utils/video_metadata). Unreadable files
are a warning, not an error: a scan over a large output tree meets
@@ -1030,7 +1034,7 @@ class PromptManagerAPI(
return read_video_metadata(image_path)
try:
with Image.open(image_path) as img:
return png_text(img)
return png_text(img) or exif_text(img)
except Exception as e:
self.logger.warning(
f"Unreadable image {os.path.basename(str(image_path))}: {e}"
+2 -1
View File
@@ -304,7 +304,8 @@ def _relative_key(path, root):
relative = os.path.relpath(str(path), str(root))
except ValueError: # another drive (Windows)
return None
return os.path.normcase(relative).replace("\\", "/")
# #646: on POSIX ``a\\b.png`` and ``a/b.png`` are two files.
return os.path.normcase(relative).replace(os.sep, "/")
@dataclass
+6 -4
View File
@@ -148,7 +148,7 @@ def folder_sets(root, files) -> tuple[frozenset, frozenset]:
folders.add(rel_dir)
with_ancestors = set(folders)
for folder in folders:
with_ancestors.update(_ancestors(folder))
with_ancestors.update(_ancestors(folder, sep))
return frozenset(folders), frozenset(with_ancestors)
@@ -158,7 +158,7 @@ def add_folder(root, path, folders, with_ancestors) -> tuple[frozenset, frozense
rel_dir = _folder_of(root, path, sep, prefix)
if not rel_dir or rel_dir in folders:
return folders, with_ancestors
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir)}
return folders | {rel_dir}, with_ancestors | {rel_dir, *_ancestors(rel_dir, sep)}
def _root_prefix(root) -> tuple[str, str]:
@@ -180,8 +180,10 @@ def _folder_of(root, path, sep, prefix) -> str:
return "" if rel_dir == "." else rel_dir
def _ancestors(folder: str) -> list[str]:
parts = folder.replace("\\", "/").split("/")
def _ancestors(folder: str, sep: str) -> list[str]:
# #646: ``\\`` separates only in a Windows root (*sep*, the root flavour's
# own); on POSIX it is part of a folder's name.
parts = (folder.replace("\\", "/") if sep == "\\" else folder).split("/")
return ["/".join(parts[:i]) for i in range(1, len(parts))]
+7 -1
View File
@@ -290,7 +290,7 @@ class ImageDeleteMixin:
acted.append(target)
counted = db.count_removal_records([t["removal"] for t in acted])
library_count = len(acted)
permanent_supported = isinstance(trash.BACKEND, trash.FreedesktopBackend)
permanent_supported = permanent_delete_supported()
public = {
"operation": IMAGE_DELETE,
"scope": {"count": library_count, "label": "images"},
@@ -570,6 +570,12 @@ class ImageDeleteMixin:
return [path for path in paths if not removed(path)]
def permanent_delete_supported() -> bool:
"""Permanent delete is offered only with the Freedesktop trash backend
(Linux/BSD servers); the review and the apply both ask here (#644)."""
return isinstance(trash.BACKEND, trash.FreedesktopBackend)
def parse_mode(value):
"""The apply's ``mode``, or None when it is not one of MODES."""
return value if isinstance(value, str) and value in MODES else None
+22 -8
View File
@@ -70,6 +70,8 @@ try:
in_trash_below_roots,
in_trash_folder,
is_skipped_folder,
path_separators,
split_relative,
)
from ...utils.parallel import map_parallel
from ...utils.json_strict import dumps_strict
@@ -101,6 +103,8 @@ except ImportError:
in_trash_below_roots,
in_trash_folder,
is_skipped_folder,
path_separators,
split_relative,
)
from utils.parallel import map_parallel
from utils.json_strict import dumps_strict
@@ -267,18 +271,23 @@ def _is_within(path, root):
def _has_traversal(relative):
"""True for absolute paths, drive-qualified paths or any ``..`` segment."""
"""True for absolute paths, drive-qualified paths or any ``..`` segment.
Segments are split at this server's separators: on POSIX ``\\`` is part
of a name, so ``a\\..\\b`` is one name below the root (#646).
"""
if not relative or os.path.isabs(relative) or os.path.splitdrive(relative)[0]:
return True
if relative[0] in ("/", "\\"):
if relative[0] in path_separators():
return True
return ".." in re.split(r"[\\/]+", relative)
return ".." in split_relative(relative)
def _is_thumbnail_cache_path(relative):
"""True when *relative* names something in a root's ``thumbnails/``
cache (any case, either separator): never inspected as a media file."""
first = re.split(r"[\\/]+", relative.lstrip("\\/"), maxsplit=1)[0]
cache (any case, this server's separators, #646): never inspected as a
media file."""
first = split_relative(relative.lstrip(path_separators()))[0]
return first.casefold() == "thumbnails"
@@ -875,7 +884,7 @@ def _favorite_root_key(root) -> str:
def _source_depth(source: str) -> int:
return len([part for part in re.split(r"[\\/]+", source) if part])
return len([part for part in split_relative(source) if part])
def deepest_source(sources, absolute_path):
@@ -1200,6 +1209,10 @@ def _output_image_entry(
}
if root_scope is not None:
entry["root_scope"] = root_scope
if "\\" in entry["path"]:
# #646: only a POSIX server lists a name holding a backslash (Windows
# turns it into ``/``); the workspace accepts it only with this mark.
entry["path_style"] = "posix"
return entry
@@ -1221,9 +1234,10 @@ def _workspace_filters(query: Mapping) -> dict:
folded = text.casefold()
media = query.get("media", "all")
order = query.get("sort", "newest")
folder = query.get("subfolder", "").strip().replace("\\", "/")
# #646: ``\\`` separates only on Windows; on POSIX it is part of a name.
folder = "/".join(split_relative(query.get("subfolder", "").strip()))
# ``path``: one exact relative path (Activity opens a scan row by it, D57).
exact = query.get("path", "").strip().replace("\\", "/")
exact = "/".join(split_relative(query.get("path", "").strip()))
category = query.get("category", "").strip() or None
tags = sorted(
{tag.strip() for tag in query.get("tags", "").split(",") if tag.strip()}
+3 -1
View File
@@ -42,6 +42,7 @@ open across the switch (#249 S8).
import asyncio
import itertools
import logging
import os
import re
import time
import uuid
@@ -160,7 +161,8 @@ def _relative_path(path) -> str:
or PureWindowsPath(text).drive
):
return re.split(r"[\\/]", text)[-1]
return text.replace("\\", "/")
# #646: on POSIX a backslash is part of a name, never a separator.
return text.replace("\\", "/") if os.sep == "\\" else text
class JobBusy(Exception):
+7 -2
View File
@@ -516,7 +516,7 @@ class MaintenanceRoutesMixin:
# ── apply ─────────────────────────────────────────────────────────
async def apply_maintenance_plan(self, request):
from .image_delete import IMAGE_DELETE, parse_mode
from .image_delete import IMAGE_DELETE, parse_mode, permanent_delete_supported
data, error = await self._read_maintenance_body(request, ("token", "mode"))
if error is not None:
@@ -531,7 +531,12 @@ class MaintenanceRoutesMixin:
if plan.operation == IMAGE_DELETE:
mode = parse_mode(data.get("mode"))
if mode is None:
return _invalid('mode must be "library" or "trash"')
return _invalid('mode must be "library", "trash" or "permanent"')
if mode == "permanent" and not permanent_delete_supported():
# The review never offers it here; refuse a direct call (#644).
return _invalid(
"Permanent delete is only available on Linux and BSD servers"
)
elif "mode" in data:
return _invalid("Unknown field: mode")
store = self._maintenance_plans
+5 -4
View File
@@ -14,10 +14,10 @@ from .prompts import bad_request
try:
from ...utils.media_capture import CAPTURE_EXTENSIONS
from ...utils.media_folders import in_trash_folder
from ...utils.media_folders import in_trash_folder, path_separators
except ImportError:
from utils.media_capture import CAPTURE_EXTENSIONS
from utils.media_folders import in_trash_folder
from utils.media_folders import in_trash_folder, path_separators
MAX_TARGET_PATH = 1024
TARGET_FIELDS = frozenset({"root_index", "root_scope", "path"})
@@ -30,7 +30,8 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
Only the listing identity is accepted: an int root index, the root's
64-hex scope and a bounded root-relative POSIX media path, never an
absolute, drive-qualified, backslash or ``..`` path (a 400 for a malformed
absolute, drive-qualified, ``..`` path, or (on Windows only, #646) one
holding a backslash (a 400 for a malformed
shape, a 403 for an unsafe or non-media path, carrying *media_message*, a
404 for a path in a trash folder, #543). A link or a short-name spelling
is refused later by the capture store's alias check.
@@ -47,7 +48,7 @@ def media_target(data: object, *, media_message: str = TAGGING_MEDIA_MESSAGE):
parts = relative.split("/")
if (
"\0" in relative
or "\\" in relative
or ("\\" in relative and "\\" in path_separators())
or relative.startswith("/")
or _has_traversal(relative)
or any(part in ("", ".", "..") or ":" in part for part in parts)
+3 -2
View File
@@ -672,12 +672,13 @@ def owns(root, path, location=None):
def is_preview_text(filepath):
"""URL text naming a preview: ``thumbnails/<...>/<name>_thumb<ext>``.
Text only, before any join: no backslash, drive or stream colon, and no
Text only, before any join: no backslash (on Windows; on POSIX it is part
of a name, #646), drive or stream colon, and no
empty, ``.`` or ``..`` segment; ``thumbnails`` exactly as the first part
and nowhere else among the folders; the extension, in any case, one a
preview may carry (``X_thumb.JPG`` of an older release included).
"""
if not filepath or "\\" in filepath or ":" in filepath:
if not filepath or ":" in filepath or (os.sep == "\\" and "\\" in filepath):
return False
parts = filepath.split("/")
if len(parts) < 2 or parts[0] != PREVIEW_FOLDER:
+6 -1
View File
@@ -146,7 +146,9 @@ def format_review_target(spelled_path, locator, real_roots, *, pathmod=os.path):
rest = rest[1:]
parts = rest.split(sep)
if any(
part in ("", ".", "..") or "/" in part or "\\" in part or ":" in part
part in ("", ".", "..") or "/" in part
# #646: on POSIX a backslash is part of a name.
or (sep == "\\" and "\\" in part) or ":" in part
for part in parts
):
continue
@@ -271,6 +273,9 @@ class ReviewRoutesMixin:
"root_scope": self._gallery_root_scope(roots[index], index),
"path": relative,
}
if "\\" in relative:
# #646: the mark the Images listing sets (POSIX only).
target["path_style"] = "posix"
# The Images listing's media URL for the same file (formatting only).
url = (
"/prompt_manager/images/serve/"
+2 -1
View File
@@ -205,7 +205,8 @@ def _is_preview_request(filepath):
take as an anchor: a backslash, a drive or stream colon, and empty, ``.``
or ``..`` segments (so a leading ``/`` and ``//server/share`` too).
"""
if "\\" in filepath or ":" in filepath:
# #646: a backslash is a separator only on Windows.
if ":" in filepath or (os.sep == "\\" and "\\" in filepath):
return False
parts = filepath.split("/")
if len(parts) < 2 or parts[0] != "thumbnails":
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "promptmanager"
description = "A powerful ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, and an automatic image gallery system using SQLite."
version = "3.6.0"
version = "3.7.1"
license = {file = "LICENSE"}
requires-python = ">=3.12"
dependencies = ["watchdog>=2.1.0", "Pillow>=10.1.0"]
+11
View File
@@ -655,6 +655,17 @@ def create_app(root: Path) -> web.Application:
shutil.copyfile(root / "output" / "shared" / "same.png", destination)
return web.json_response({"success": True})
@routes.post("/__test__/add-backslash-image")
async def add_backslash_image(request: web.Request) -> web.Response:
"""#646: a folder whose name holds a backslash, as a Windows-style
``filename_prefix`` makes on a POSIX server."""
if os.sep == "\\":
return web.json_response({"success": False}, status=409)
destination = root / "output" / "model.safetensors\\2026-11-17" / "slash.png"
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(root / "output" / "shared" / "same.png", destination)
return web.json_response({"success": True})
@routes.post("/__test__/add-local-inspect-file")
async def add_local_inspect_file(request: web.Request) -> web.Response:
"""Serve one committed Inspect fixture from the output folder.
+23
View File
@@ -2709,3 +2709,26 @@ test('all matching over 10,000 images says so before any dialog or request', asy
}
expect(posted).toBe(0);
});
// #646: on a POSIX server a Windows-style filename_prefix makes one folder whose name holds a backslash. Its file opens
// in the viewer, takes a star that survives a reload, and the folder filter names it with its backslash.
test('a file in a folder whose name holds a backslash opens, stars and filters (#646)', async ({ page, request }) => {
await expect(await request.post('/__test__/add-backslash-image')).toBeOK();
await page.goto(workspace);
await expect(cards(page)).toHaveCount(3);
const card = page.locator('article[data-image-key="0:model.safetensors\\\\2026-11-17/slash.png"]');
await card.locator('.image-open').click();
const viewer = page.locator('dialog#viewer-dialog[open]');
await expect(viewer.locator('#viewer-title')).toContainText('slash.png');
await expect(viewer.locator('#viewer-details .panel-heading')).toBeVisible();
await viewer.locator('#viewer-close').click();
await expect(viewer).toHaveCount(0);
await star(card, 'slash.png').click();
await expectStar(star(card, 'slash.png'), true);
await expect.poll(async () => (await listedFavorites(request))['0:model.safetensors\\2026-11-17/slash.png']).toBe(true);
await page.reload();
await expectStar(star(card, 'slash.png'), true);
await refine(page, { Folder: 'model.safetensors\\2026-11-17' });
await expect(cards(page)).toHaveCount(1);
await expect(cards(page)).toContainText('slash.png');
});
+4 -2
View File
@@ -565,9 +565,11 @@ test('URLs and media end with their owning session', async ({ page }) => {
// Replacement.
await choose(page, parityPng('f02.png'));
await expect(preview(page).locator('img.local-file-preview')).toBeVisible();
// #653: a video still starting (inline, or in the viewer the selection opened) is held until it settles or
// STARTING_VIDEO_MS (15 s) passes, so its release can follow the new preview: wait for it, never check once.
let state = await urls(page);
expect(state.revoked).toEqual([state.created[0]]);
expect(await page.evaluate(() => window.__loads)).toBeGreaterThanOrEqual(1);
await expect.poll(async () => (await urls(page)).revoked, { timeout: 20000 }).toEqual([state.created[0]]);
await expect.poll(() => page.evaluate(() => window.__loads), { timeout: 20000 }).toBeGreaterThanOrEqual(1);
// Route change, from the page (D155: the selection opened the viewer, which makes the sidebar inert).
await closeOpened(page);
await page.locator('aside.sidebar nav').getByRole('link', { name: 'Overview', exact: true }).click();
@@ -954,3 +954,15 @@ test('record accepts an image\'s own category on any link status (#332)', () =>
assert.equal(record.library.category_scope, 'image');
}
});
test('a backslash inside a name is accepted only from a POSIX listing (#646)', () => {
const inspectPath = contract('inspectPath');
const path = 'model.safetensors\\2026-11-17/a.png';
assert.equal(inspectPath({root_index:0, path, root_scope:scopeA, path_style:'posix'}),
`/prompt_manager/images/inspect/model.safetensors%5C2026-11-17/a.png?root=0&root_scope=${scopeA}`);
for (const path_style of [undefined, 'windows', 'POSIX'])
assert.throws(() => inspectPath({root_index:0, path, root_scope:scopeA, path_style}), /Invalid inspection identity/);
// The mark relaxes only the backslash: traversal, drives and empty names stay refused.
for (const bad of ['../a.png', 'a/../b.png', 'C:\\a.png', 'a//b.png', '/a.png'])
assert.throws(() => inspectPath({root_index:0, path:bad, root_scope:scopeA, path_style:'posix'}), /Invalid inspection identity/);
});
+25
View File
@@ -0,0 +1,25 @@
// #646: Needs review hands the viewer and inspector the same identity the Images listing does, the POSIX mark
// for a name holding a backslash included.
import test from 'node:test';
import assert from 'node:assert/strict';
import { imageOf } from '../../web/js/workspace/review.mjs';
import { inspectPath } from '../../web/js/workspace/inspection-state.mjs';
const scope = 'a'.repeat(64);
const item = target => ({ filename: 'a.png', target, url: '/u', thumbnail_url: null, is_video: false });
test('a review item keeps the POSIX mark of a name holding a backslash', () => {
const path = 'm.safetensors\\2026-11-17/a.png';
const image = imageOf(item({ root_index: 0, root_scope: scope, path, path_style: 'posix' }));
assert.equal(image.path_style, 'posix');
assert.equal(inspectPath(image), `/prompt_manager/images/inspect/m.safetensors%5C2026-11-17/a.png?root=0&root_scope=${scope}`);
});
test('a review item without the mark, or with another value, carries none', () => {
for (const path_style of [undefined, 'windows', 'POSIX']) {
const image = imageOf(item({ root_index: 0, root_scope: scope, path: 'a\\b.png', path_style }));
assert.equal(Object.hasOwn(image, 'path_style'), false);
assert.throws(() => inspectPath(image), /Invalid inspection identity/);
}
assert.equal(Object.hasOwn(imageOf(item({ root_index: 0, root_scope: scope, path: 'p/a.png' })), 'path_style'), false);
});
+17 -1
View File
@@ -225,7 +225,12 @@ class TestObserve(AnnotationAPITestCase):
("dot segment", {"path": "./a.png"}, 403),
("empty segment", {"path": "sub//a.png"}, 403),
("absolute", {"path": "/etc/a.png"}, 403),
("backslash", {"path": "sub\\a.png"}, 403),
# #646: a backslash is a separator only on Windows.
*(
[("backslash", {"path": "sub\\a.png"}, 403)]
if os.sep == "\\"
else []
),
("drive", {"path": "C:/a.png"}, 403),
("drive segment", {"path": "sub/C:a.png"}, 403),
("nul", {"path": "a\x00.png"}, 403),
@@ -399,6 +404,17 @@ class TestObserve(AnnotationAPITestCase):
self.assertEqual(response.headers["Content-Type"], "video/mp4")
self.assertEqual(await response.read(), clip.read_bytes())
@unittest.skipIf(os.sep == "\\", "a backslash cannot be in a Windows name")
async def test_a_backslash_inside_a_name_can_be_tagged_on_posix(self):
# #646: a Windows-style filename_prefix makes such a folder on POSIX.
path = "m.safetensors\\2026-11-17/a.png"
make_png(self.output_dir / "m.safetensors\\2026-11-17" / "a.png")
observed = await self.observe_ok(path)
self.assertEqual(observed["target"]["path"], path)
status, body = await self.put_tags(self.save_body(observed, ["forest"]))
self.assertEqual(status, 200, body)
self.assertEqual((await self.observe_ok(path))["tags"], ["forest"])
async def test_observe_maps_capture_outcomes_to_codes(self):
make_png(self.output_dir / "sub" / "a.png")
outside = make_png(self.comfy_dir / "outside.png")
+3 -1
View File
@@ -2,6 +2,7 @@
import json
import ntpath
import os
import sqlite3
from unittest.mock import patch
@@ -178,7 +179,8 @@ class TestCollectionRoutes(CollectionRoutesTestCase):
"../a.png",
"sub/../../a.png",
"C:/a.png",
"a\\b.png",
# #646: a backslash is a separator only on Windows.
*(["a\\b.png"] if os.sep == "\\" else []),
"/a.png",
"notes.txt",
):
+18
View File
@@ -926,6 +926,24 @@ class TestMetadataParsing(unittest.TestCase):
f.write(b"nope")
self.assertEqual(self.api._extract_comfyui_metadata(garbage), {})
def test_extract_metadata_from_webp_exif(self):
"""SaveAnimatedWEBP writes the records as EXIF, with no text chunks."""
from PIL import Image
path = os.path.join(self.tmpdir, "m.webp")
exif = Image.Exif()
exif[0x0110] = 'prompt:{"1": {"class_type": "KSampler"}}'
exif[0x010F] = 'workflow:{"nodes": [{"type": "CLIPTextEncode"}]}'
Image.new("RGB", (1, 1)).save(path, "WEBP", exif=exif)
self.assertEqual(
self.api._extract_comfyui_metadata(path),
{
"prompt": '{"1": {"class_type": "KSampler"}}',
"workflow": '{"nodes": [{"type": "CLIPTextEncode"}]}',
},
)
if __name__ == "__main__":
unittest.main()
+4 -1
View File
@@ -2,6 +2,7 @@
import json
import ntpath
import os
import sqlite3
from unittest.mock import patch
@@ -272,7 +273,9 @@ class TestRefusals(ImageCategoryTestCase):
async def test_unsafe_paths_are_403(self):
(self.output_dir / "notes.txt").write_text("not media")
for path in ("../outside.png", "/a.png", "C:/a.png", "a\\b.png", "a/./b.png"):
# #646: a backslash is a separator only on Windows.
windows = ["a\\b.png"] if os.sep == "\\" else []
for path in ("../outside.png", "/a.png", "C:/a.png", *windows, "a/./b.png"):
with self.subTest(path=path):
await self.put([self.target(path)], "x", status=403)
data = await self.put([self.target("notes.txt")], "x", status=403)
+20 -1
View File
@@ -1268,7 +1268,12 @@ class TestPathHelpers(unittest.TestCase):
def test_has_traversal(self):
self.assertTrue(images_module._has_traversal(""))
self.assertTrue(images_module._has_traversal("a/../b.png"))
self.assertTrue(images_module._has_traversal("\\\\srv\\share\\x.png"))
# #646: on POSIX a backslash is part of a name, so a UNC spelling is one
# name below the root; on Windows it re-anchors the path.
self.assertEqual(
images_module._has_traversal("\\\\srv\\share\\x.png"), os.sep == "\\"
)
self.assertEqual(images_module._has_traversal("a\\..\\b.png"), os.sep == "\\")
self.assertTrue(images_module._has_traversal(os.path.abspath(os.sep)))
self.assertFalse(images_module._has_traversal("sub/x.png"))
@@ -2735,6 +2740,20 @@ class TestSharedListing(ImageAPITestCase):
delay.start()
self.addCleanup(delay.stop)
async def tearDownAsync(self):
# A read that stores a listing starts the workspace cache build, which
# opens the database on a worker thread; cancelling its task at cleanup
# does not stop the thread. A test that ends on that read must let it
# finish, or teardown can find its connection open (queue run
# 44164234834, py3.14). No new build starts from here on; a held walk
# is not waited for (its scan never opens the database).
self.api._workspace_warm_enabled = False
if self._warming():
await asyncio.wait_for(
asyncio.shield(self.api._workspace_warm_task), _HANG_LIMIT
)
await super().tearDownAsync()
async def _json(self, method, path, **kwargs):
# Bounded, like every wait in this class: a stuck walk fails the test
# with a traceback instead of hanging the whole run.
+6 -1
View File
@@ -2,6 +2,7 @@
import io
import json
import os
import shutil
import subprocess
import unittest
@@ -151,7 +152,8 @@ class TestPromptInspector(ImageAPITestCase):
for path in (
"%2Fetc%2Fpasswd.png",
"..%2Fsecret.png",
"%5Csecret.png",
# #646: on POSIX a backslash is part of a name (404 below).
*(["%5Csecret.png"] if os.sep == "\\" else []),
"bad.txt",
"null%00.png",
"C:%5Csecret.png",
@@ -160,6 +162,9 @@ class TestPromptInspector(ImageAPITestCase):
self.assertEqual(response.status, 403, path)
response, result = await self.inspect("missing.png")
self.assertEqual(response.status, 404)
if os.sep == "/":
response, result = await self.inspect("%5Csecret.png")
self.assertEqual(response.status, 404)
outside = png(self.comfy_dir / "outside.png", prompt=graph("private"))
self._make_symlink(outside, self.output_dir / "escape.png")
response, result = await self.inspect("escape.png")
+2 -1
View File
@@ -149,7 +149,8 @@ class TestRescopeRoute(ImageAPITestCase):
{"target": {**good, "path": "../a.png"}},
{"target": {**good, "path": "/abs.png"}},
{"target": {**good, "path": "C:/a.png"}},
{"target": {**good, "path": "sub\\a.png"}},
# #646: a backslash is a separator only on Windows.
*([{"target": {**good, "path": "sub\\a.png"}}] if os.sep == "\\" else []),
{"target": {**good, "path": "sub//a.png"}},
{"target": {**good, "path": "notes.txt"}},
{"target": {**good, "path": "x" * 2000 + ".png"}},
+17
View File
@@ -14,6 +14,7 @@ import os
import posixpath
import sqlite3
import threading
import unittest
from pathlib import Path
from unittest.mock import patch
@@ -452,6 +453,22 @@ class TestQueueReads(ReviewRoutesTestCase):
)
class TestBackslashNames(ReviewRoutesTestCase):
"""#646: a review item in a folder whose name holds a backslash (POSIX)."""
@unittest.skipIf(os.sep == "\\", "a backslash cannot be in a Windows name")
async def test_the_target_carries_the_posix_mark(self):
self._require_routes()
self._record(self._ambiguous("m.safetensors\\2026-11-17/a.png"))
self._record(self._ambiguous("plain/b.png", color=(0, 255, 0)))
items = {item["filename"]: item for item in (await self._list())["items"]}
marked = items["a.png"]["target"]
self.assertEqual(marked["path"], "m.safetensors\\2026-11-17/a.png")
self.assertEqual(marked["path_style"], "posix")
self.assertFalse(items["a.png"]["unavailable"])
self.assertNotIn("path_style", items["b.png"]["target"])
class TestDecisions(ReviewRoutesTestCase):
async def test_apply_candidate_links_pair_and_records_decision_atomically(self):
self._require_routes()
+6
View File
@@ -273,6 +273,12 @@ class TestNodeIntegration(unittest.TestCase):
# Check optional inputs
self.assertIn("search_text", input_types["optional"])
# Every optional STRING starts empty, so the schema offers "" and not
# null: the composition sockets used to be the only ones without a
# default, although the node already treats them as empty.
for name in ("category", "tags", "search_text", "prepend_text", "append_text"):
self.assertEqual(input_types["optional"][name][1]["default"], "", name)
if __name__ == "__main__":
unittest.main()
+131
View File
@@ -0,0 +1,131 @@
"""ComfyUI's EXIF records: what WebP, AVIF and JPEG carry instead of text.
ComfyUI's SaveAnimatedWEBP writes ``prompt:{json}`` to EXIF tag 0x0110, then
``workflow:{json}`` and every other ``extra_pnginfo`` key to 0x010F and down;
the AVIF writer uses that layout too. Pillow exposes them only through
``getexif()``, so a reader that looks at ``image.info`` or the text chunks
finds nothing. These tests write real files in that layout.
"""
import json
import os
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from PIL import Image, features
from utils.exif_text import exif_text
PROMPT = {"1": {"class_type": "KSampler", "inputs": {"seed": 7}}}
WORKFLOW = {"nodes": [{"type": "CLIPTextEncode", "inputs": {"text": "cat"}}]}
PAIRS = [{"positive": "cat", "negative": "dog"}]
def comfyui_exif(prompt=PROMPT, extra=None):
"""The tags ComfyUI writes: the prompt on 0x0110, extra_pnginfo from 0x010F."""
exif = Image.Exif()
if prompt is not None:
exif[0x0110] = f"prompt:{json.dumps(prompt)}"
tag = 0x010F
for key, value in ({"workflow": WORKFLOW} if extra is None else extra).items():
exif[tag] = f"{key}:{json.dumps(value)}"
tag -= 1
return exif
class ExifTextCase(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.folder = folder.name
def write(self, name, image_format, exif, **options):
path = os.path.join(self.folder, name)
Image.new("RGB", (8, 8), "red").save(path, image_format, exif=exif, **options)
return path
def read(self, path):
with Image.open(path) as image:
return exif_text(image)
class TestComfyuiRecords(ExifTextCase):
def test_reads_the_records_of_a_webp(self):
path = self.write("a.webp", "WEBP", comfyui_exif())
self.assertEqual(
self.read(path),
{"prompt": json.dumps(PROMPT), "workflow": json.dumps(WORKFLOW)},
)
def test_reads_an_animated_webp(self):
# SaveAnimatedWEBP writes the first frame's EXIF and appends the rest.
frames = [Image.new("RGB", (8, 8), color) for color in ("red", "blue")]
path = os.path.join(self.folder, "anim.webp")
frames[0].save(
path,
"WEBP",
save_all=True,
append_images=frames[1:],
duration=100,
exif=comfyui_exif(),
)
self.assertEqual(self.read(path)["workflow"], json.dumps(WORKFLOW))
def test_reads_every_extra_pnginfo_key_and_not_only_the_workflow(self):
exif = comfyui_exif(
extra={"workflow": WORKFLOW, "comfyassets_prompt_pairs": PAIRS}
)
path = self.write("pairs.webp", "WEBP", exif)
self.assertEqual(self.read(path)["comfyassets_prompt_pairs"], json.dumps(PAIRS))
def test_reads_a_jpeg_in_the_same_layout(self):
# Not a core saver, but a third-party one reusing the convention.
path = self.write("a.jpg", "JPEG", comfyui_exif())
self.assertEqual(self.read(path)["prompt"], json.dumps(PROMPT))
@unittest.skipUnless(features.check("avif"), "Pillow has no AVIF support")
def test_reads_an_avif(self):
path = self.write("a.avif", "AVIF", comfyui_exif())
self.assertEqual(self.read(path)["workflow"], json.dumps(WORKFLOW))
class TestOtherExif(ExifTextCase):
def test_a_camera_exif_is_not_a_comfyui_record(self):
exif = Image.Exif()
exif[0x010F] = "Canon" # Make
exif[0x0110] = "Canon EOS R5" # Model
exif[0x0131] = "GIMP 2.10.38" # Software
exif[0x0132] = "2024:01:02 03:04:05" # DateTime
path = self.write("camera.jpg", "JPEG", exif)
self.assertEqual(self.read(path), {})
def test_a_value_that_is_not_json_is_not_a_record(self):
exif = Image.Exif()
exif[0x010E] = "note:not json"
exif[0x010D] = "make:Canon"
path = self.write("notes.webp", "WEBP", exif)
self.assertEqual(self.read(path), {})
def test_a_png_answers_empty_its_records_are_text_chunks(self):
from PIL.PngImagePlugin import PngInfo
info = PngInfo()
info.add_text("workflow", json.dumps(WORKFLOW))
path = os.path.join(self.folder, "a.png")
Image.new("RGB", (8, 8)).save(path, pnginfo=info)
self.assertEqual(self.read(path), {})
if __name__ == "__main__":
unittest.main()
+23 -2
View File
@@ -428,10 +428,31 @@ class TestPermanentMode(ImageDeleteTestCase):
else:
self.assertFalse(plan.get("permanent_delete_supported"))
async def test_permanent_is_refused_where_the_review_does_not_offer_it(self):
"""#644: without the Freedesktop backend the apply answers 400 for
"permanent" before any backup, and the file and its records stay."""
from utils import trash
fake_trash.uninstall()
self.addCleanup(fake_trash.uninstall)
self.write("a.png", b"aaa", mtime=1_000_000)
self.link("a.png")
with patch.object(trash, "BACKEND", trash.UnavailableBackend()):
plan = await self.review(["a.png"])
self.assertFalse(plan["permanent_delete_supported"])
with patch("os.remove") as remove:
body = await self.post(
APPLY, {"token": plan["token"], "mode": "permanent"}, 400
)
remove.assert_not_called()
self.assertIn("Linux", body["error"])
self.assertTrue((self.output_dir / "a.png").exists())
self.assertEqual(self.count("SELECT COUNT(*) FROM generated_images"), 1)
async def test_permanent_delete_removes_the_file(self):
fake_trash.uninstall()
self.addCleanup(fake_trash.uninstall)
if sys.platform == "win32":
if not image_delete.permanent_delete_supported():
self.skipTest("permanent delete is Linux/BSD only")
self.write("a.png", b"aaa", mtime=1_000_000)
self.link("a.png")
@@ -453,7 +474,7 @@ class TestPermanentMode(ImageDeleteTestCase):
fake_trash.uninstall()
self.addCleanup(fake_trash.uninstall)
if sys.platform == "win32":
if not image_delete.permanent_delete_supported():
self.skipTest("permanent delete is Linux/BSD only")
self.write("a.png", b"aaa", mtime=1_000_000)
self.link("a.png")
+5 -1
View File
@@ -1045,7 +1045,8 @@ class TestRevealRoute(ImageAPITestCase):
for path in (
"../outside.png",
"sub/../../outside.png",
"sub\\..\\..\\outside.png",
# #646: a separator only on Windows; on POSIX one name (below).
*(["sub\\..\\..\\outside.png"] if os.sep == "\\" else []),
str(outside),
"/" + outside.name,
"C:/outside.png",
@@ -1054,6 +1055,9 @@ class TestRevealRoute(ImageAPITestCase):
with self.subTest(path=path):
status, data = await self.post(self.body(path=path))
self.assertEqual(status, 400, data)
if os.sep == "/":
status, data = await self.post(self.body(path="sub\\..\\..\\outside.png"))
self.assertEqual(status, 404, data)
self.assertEqual(self.opened, [])
async def test_symlink_out_of_the_root_is_refused(self):
+14 -1
View File
@@ -135,6 +135,18 @@ class CaptureStoreTestCase(unittest.TestCase):
# -- exact bytes and identity -------------------------------------------
@unittest.skipIf(os.sep == "\\", "a backslash cannot be in a Windows name")
def test_a_backslash_inside_a_name_is_captured_on_posix(self):
# #646: a Windows-style filename_prefix makes such a folder on POSIX.
data = png_bytes(2, 2, b"backslash")
self.write("m.safetensors\\2026-11-17/a.png", data)
store = self.make_store()
cap = self.capture(store, "m.safetensors\\2026-11-17/a.png")
try:
self.assertEqual(Path(cap.path).read_bytes(), data)
finally:
store.release(cap.token)
def test_capture_hashes_and_copies_exact_bytes_owner_only(self):
source_bytes = png_bytes(3, 2, os.urandom(40))
source = self.write("a.png", source_bytes)
@@ -212,7 +224,8 @@ class CaptureStoreTestCase(unittest.TestCase):
"",
"/a.png",
"C:/a.png",
"a\\b.png",
# #646: a backslash separates folders only on Windows.
*(["a\\b.png"] if os.sep == "\\" else []),
"a\x00.png",
"notes.txt",
"folder",
+38
View File
@@ -39,3 +39,41 @@ class TrashFolderNameTests(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
class ServerSeparatorTests(unittest.TestCase):
"""#646: ``\\`` separates names only on Windows; on POSIX it is part of one."""
def test_posix_keeps_a_backslash_inside_one_name(self):
import posixpath
from utils.media_folders import path_separators, split_relative
self.assertEqual(path_separators(posixpath), "/")
self.assertEqual(
split_relative("m.safetensors\\2026-11-17/x.png", posixpath),
["m.safetensors\\2026-11-17", "x.png"],
)
self.assertEqual(split_relative("a\\..\\b", posixpath), ["a\\..\\b"])
def test_windows_splits_on_both(self):
import ntpath
from utils.media_folders import path_separators, split_relative
self.assertEqual(path_separators(ntpath), "/\\")
self.assertEqual(
split_relative("m.safetensors\\2026-11-17/x.png", ntpath),
["m.safetensors", "2026-11-17", "x.png"],
)
self.assertEqual(split_relative("a\\..\\b", ntpath), ["a", "..", "b"])
def test_trash_detection_follows_the_server_separators(self):
import ntpath
import posixpath
from utils.media_folders import in_trash_folder
self.assertTrue(in_trash_folder(".Trash-1000\\x.png", ntpath))
self.assertFalse(in_trash_folder(".Trash-1000\\x.png", posixpath))
self.assertTrue(in_trash_folder("a/.Trash-1000/x.png", posixpath))
+41
View File
@@ -41,6 +41,31 @@ def _create_png(text_chunks=None, size=(64, 64)):
return tmp.name
def _create_webp(workflow=None, prompt=None, size=(64, 64)):
"""Create a minimal WebP with the EXIF records ComfyUI writes.
SaveAnimatedWEBP puts ``prompt:{json}`` at EXIF tag 0x0110 and
``workflow:{json}`` at 0x010F; the file has no text chunks at all.
Args:
workflow: Workflow dict to embed as the workflow record.
prompt: Prompt dict to embed as the prompt record.
size: tuple (width, height).
Returns:
Path to the temporary WebP file.
"""
exif = Image.Exif()
if prompt is not None:
exif[0x0110] = f"prompt:{json.dumps(prompt)}"
if workflow is not None:
exif[0x010F] = f"workflow:{json.dumps(workflow)}"
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".webp")
tmp.close()
Image.new("RGB", size, color=(128, 128, 128)).save(tmp.name, "WEBP", exif=exif)
return tmp.name
class MetadataTestCase(unittest.TestCase):
"""Base class that cleans up temp files."""
@@ -58,6 +83,11 @@ class MetadataTestCase(unittest.TestCase):
self.temp_files.append(path)
return path
def _webp(self, workflow=None, prompt=None, size=(64, 64)):
path = _create_webp(workflow, prompt, size)
self.temp_files.append(path)
return path
class TestExtractMetadata(MetadataTestCase):
"""Test extract_metadata method."""
@@ -82,6 +112,17 @@ class TestExtractMetadata(MetadataTestCase):
self.assertIsNotNone(result)
self.assertIn("prompt", result)
def test_extracts_metadata_from_webp_exif(self):
"""A WebP carries the records as EXIF, not as text chunks."""
workflow = {"nodes": [{"type": "CLIPTextEncode", "inputs": {"text": "hi"}}]}
prompt = {"1": {"class_type": "KSampler", "inputs": {}}}
path = self._webp(workflow=workflow, prompt=prompt)
result = self.extractor.extract_metadata(path)
self.assertIsNotNone(result)
self.assertEqual(result["workflow"]["nodes"][0]["type"], "CLIPTextEncode")
self.assertIn("prompt", result)
self.assertEqual(result["file_info"]["format"], "WEBP")
def test_extracts_text_encoder_nodes(self):
workflow = {
"nodes": [
+139
View File
@@ -0,0 +1,139 @@
"""A backslash inside a file or folder name on a POSIX server (#646).
A Windows-style ``filename_prefix`` (``model\\2026-11-17/name``) makes, on
Linux or macOS, one folder whose name holds a backslash. The listing names it;
every route that takes a listing path accepts it there, and keeps refusing it
on Windows, where a backslash separates folders.
"""
import ntpath
import os
import posixpath
import unittest
from unittest.mock import patch
try:
from tests.test_image_delete_routes import ImageDeleteTestCase
except ImportError: # discovered with tests/ as the top-level directory
from test_image_delete_routes import ImageDeleteTestCase
from py.api import images, media_target as media_target_module
from py.api.media_target import media_target
from utils.media_folders import split_relative
POSIX_ONLY = unittest.skipIf(os.sep == "\\", "a backslash cannot be in a Windows name")
FOLDER = "model.safetensors\\2026-11-17"
NAME = f"{FOLDER}/a.png"
SCOPE = "a" * 64
class TestTargetsOnEitherServer(unittest.TestCase):
"""``media_target`` follows the server's separators; patched to try both."""
def check(self, separators, path):
pathmod = ntpath if "\\" in separators else posixpath
with (
patch.object(media_target_module, "path_separators", lambda: separators),
patch.object(images, "path_separators", lambda: separators),
patch.object(
images, "split_relative", lambda text: split_relative(text, pathmod)
),
):
return media_target({"root_index": 0, "root_scope": SCOPE, "path": path})
def test_posix_accepts_a_backslash_inside_a_name(self):
for path in (NAME, "a\\..\\b.png", "a\\b.png"):
with self.subTest(path=path):
target, error = self.check("/", path)
self.assertIsNone(error)
self.assertEqual(target, (0, SCOPE, path))
def test_posix_still_refuses_traversal_and_absolute_paths(self):
for path in ("../a.png", "a/../b.png", "/a.png", "a//b.png", "./a.png"):
with self.subTest(path=path):
self.assertIsNotNone(self.check("/", path)[1])
def test_windows_refuses_every_backslash(self):
for path in (NAME, "a\\..\\b.png", "\\a.png", "C:\\a.png", "a\\b.png"):
with self.subTest(path=path):
self.assertIsNotNone(self.check("/\\", path)[1])
def test_traversal_check_splits_at_the_server_separators(self):
self.assertEqual(split_relative("a\\..\\b", posixpath), ["a\\..\\b"])
self.assertIn("..", split_relative("a\\..\\b", ntpath))
if os.sep == "/":
self.assertFalse(images._has_traversal("a\\..\\b.png"))
self.assertFalse(images._has_traversal(NAME))
self.assertTrue(images._has_traversal("a/../b.png"))
self.assertTrue(images._has_traversal("/a.png"))
@POSIX_ONLY
class TestPosixRoutes(ImageDeleteTestCase):
async def page(self, **params):
response = await self.client.get(
"/prompt_manager/images/output", params={"mode": "workspace", **params}
)
self.assertEqual(response.status, 200)
return {image["path"]: image for image in (await response.json())["images"]}
async def test_the_listing_marks_only_a_path_with_a_backslash(self):
self.write(NAME, b"aaa")
self.write("plain/b.png", b"bbb")
listed = await self.page()
self.assertEqual(listed[NAME]["path_style"], "posix")
self.assertNotIn("path_style", listed["plain/b.png"])
async def test_the_folder_filter_names_the_folder_with_its_backslash(self):
self.write(NAME, b"aaa")
self.write("model.safetensors/2026-11-17/b.png", b"bbb")
self.assertEqual(list(await self.page(subfolder=FOLDER)), [NAME])
self.assertEqual(
list(await self.page(subfolder="model.safetensors/2026-11-17")),
["model.safetensors/2026-11-17/b.png"],
)
self.assertEqual(list(await self.page(path=NAME)), [NAME])
async def test_a_favorite_lands_on_the_file_it_names(self):
self.write(NAME, b"aaa")
self.write("model.safetensors/2026-11-17/a.png", b"bbb")
response = await self.client.put(
"/prompt_manager/images/favorite",
json={"root_index": 0, "path": NAME, "favorite": True},
)
self.assertEqual(response.status, 200, await response.text())
listed = await self.page()
self.assertTrue(listed[NAME]["favorite"])
self.assertFalse(listed["model.safetensors/2026-11-17/a.png"]["favorite"])
async def test_a_collection_takes_the_file(self):
self.write(NAME, b"aaa")
response = await self.client.post(
"/prompt_manager/collections/items",
json={"name": "c", "items": [self.target(NAME)]},
)
self.assertLess(response.status, 300, await response.text())
collections = await (
await self.client.get("/prompt_manager/collections")
).json()
[collection] = [c["id"] for c in collections["collections"] if c["name"] == "c"]
self.assertEqual(list(await self.page(collection=str(collection))), [NAME])
async def test_delete_moves_only_that_file_to_the_trash(self):
self.write(NAME, b"aaa")
twin = self.write("model.safetensors/2026-11-17/a.png", b"bbb")
_plan, job = await self.delete([NAME], "trash")
self.assertEqual(job.state, "finished", job.summary())
self.assertFalse((self.output_dir / NAME).exists())
self.assertTrue(twin.exists())
[(source, _destination)] = self.fake.moved
self.assertEqual(source, str(self.output_dir / NAME))
async def test_a_backslash_never_reaches_outside_the_root(self):
# ``a\..\b.png`` is one name below the root on POSIX, not a way out of it.
self.write("a\\..\\b.png", b"aaa")
outside = self.write("b.png", b"bbb", folder=self.outside_dir)
_plan, job = await self.delete(["a\\..\\b.png"], "trash")
self.assertEqual(job.state, "finished", job.summary())
self.assertTrue(outside.exists())
self.assertFalse((self.output_dir / "a\\..\\b.png").exists())
+7 -2
View File
@@ -434,7 +434,8 @@ class TestThumbnailOnFirstView(AutoThumbnailCase):
for path in (
"thumbnails/D:/x_thumb.webp",
"thumbnails/D:x_thumb.webp",
"thumbnails/\\\\server\\share/x_thumb.webp",
# #646: a backslash re-anchors a join only on Windows.
*(["thumbnails/\\\\server\\share/x_thumb.webp"] if os.sep == "\\" else []),
"thumbnails//server/share/x_thumb.webp",
"/thumbnails/x_thumb.webp",
"thumbnails/a/./x_thumb.webp",
@@ -451,7 +452,11 @@ class TestThumbnailOnFirstView(AutoThumbnailCase):
):
for path in (
"thumbnails/D:/x_thumb.webp",
"thumbnails/\\\\server\\share/x_thumb.webp",
*(
["thumbnails/\\\\server\\share/x_thumb.webp"]
if os.sep == "\\"
else []
),
"/thumbnails/x_thumb.webp",
):
answer = await self.api._serve_missing_thumbnail(
+6 -1
View File
@@ -7,7 +7,9 @@ developer's machine a missing short name or symlink right is a failure.
"""
import ctypes
import ntpath
import os
import posixpath
import unittest
import urllib.parse
from pathlib import Path
@@ -300,7 +302,10 @@ class TestPredicates(unittest.TestCase):
self.assertFalse(is_trash_folder(name), name)
def test_either_separator(self):
self.assertTrue(in_trash_folder("a\\.Trash\\b.png"))
# #646: a backslash separates only on Windows.
self.assertTrue(in_trash_folder("a\\.Trash\\b.png", ntpath))
self.assertFalse(in_trash_folder("a\\.Trash\\b.png", posixpath))
self.assertTrue(in_trash_folder("a/.Trash/b.png"))
self.assertFalse(in_trash_folder(".Trash"))
def test_a_path_no_root_visibly_holds_fails_closed(self):
+11 -1
View File
@@ -51,7 +51,17 @@ class TestMapParallel(unittest.TestCase):
def test_jobs_reuse_the_same_long_lived_threads(self):
"""Arenas are reused instead of a new set of threads per job."""
first, second = set(), set()
map_parallel(lambda _: first.add(threading.current_thread()), range(8), 2)
# The pool starts threads lazily: tiny tasks could all run on the first
# thread and leave the second to start in the next job (queue run
# 44169912829). The barrier makes the first job run on both.
both = threading.Barrier(2)
def meet(_):
first.add(threading.current_thread())
both.wait(WAIT)
map_parallel(meet, range(8), 2)
self.assertEqual(len(first), 2, first)
map_parallel(lambda _: second.add(threading.current_thread()), range(8), 2)
self.assertTrue(second <= first, (first, second))
self.assertLessEqual(len(_job_threads()), 2)
+47
View File
@@ -0,0 +1,47 @@
"""ComfyUI's EXIF metadata records (WebP, AVIF, JPEG).
PNG keeps the workflow and the prompt in text chunks (``utils.png_text``).
The formats without text chunks carry the same records as EXIF strings:
``SaveAnimatedWEBP`` writes ``prompt:{json}`` to tag 0x0110, then
``workflow:{json}`` and every other ``extra_pnginfo`` key to 0x010F and down,
and the AVIF writer uses that layout too. Pillow answers those tags only
through ``getexif()``; ``image.info`` holds the raw EXIF blob, so reading it
as text found no metadata at all.
``exif_text`` returns the ``{key: json}`` shape of ``utils.png_text`` so a
caller reads either source the same way. Only a value shaped like a ComfyUI
record counts, a key and a colon followed by a JSON object, array or string;
a camera's ``Make`` or a ``DateTime`` is not metadata.
"""
import re
# A record's key: ``workflow``, ``prompt`` or an extra_pnginfo key.
_KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
# What a record holds: the workflow and the prompt are objects, the pair
# records a list, a custom extra_pnginfo value may be a string. Numbers,
# dates and camera names start with anything else.
_STARTS = ("{", "[", '"')
def exif_text(image) -> dict:
"""ComfyUI's EXIF records of an opened image, or ``{}``.
The image stays usable and nothing is decoded but the EXIF block. Formats
whose records are text chunks (PNG) answer ``{}``; read those with
``utils.png_text.png_text`` first.
"""
try:
exif = image.getexif()
except Exception: # a broken EXIF block never fails a scan
return {}
records = {}
for value in exif.values():
if isinstance(value, bytes):
value = value.decode("utf-8", errors="replace")
if not isinstance(value, str):
continue
key, separator, payload = value.partition(":")
if separator and _KEY.match(key) and payload.lstrip()[:1] in _STARTS:
records[key] = payload
return records
+2 -2
View File
@@ -45,7 +45,7 @@ from .foreign_runs import (
store_foreign,
)
from .hashing import generate_prompt_hash
from .media_folders import in_skipped_folder
from .media_folders import in_skipped_folder, split_relative
from .metadata_extractor import ComfyUIMetadataExtractor
from .parallel import note_refusal, refused_at_shutdown
from .logging_config import get_logger
@@ -519,7 +519,7 @@ class ImageGenerationHandler(FileSystemEventHandler):
]
if holding:
text = text[len(os.path.join(max(holding, key=len), "")) :]
return text.replace("\\", "/").split("/")[:-1]
return split_relative(text)[:-1]
def process_new_image(self, image_path: str, prompt_snapshot=None):
"""Process a newly created image file for gallery integration.
+6 -2
View File
@@ -659,12 +659,16 @@ def header_dimensions(path: str) -> tuple[int, int]:
def _relative_parts(relative) -> tuple[list[str], str]:
"""Split a safe relative POSIX media path; anything else is denied."""
"""Split a safe relative POSIX media path; anything else is denied.
A backslash is denied on Windows, where it separates folders; on POSIX it
is part of a name (#646), and ``_resolve`` still checks the joined path.
"""
if not isinstance(relative, str) or not relative:
raise CaptureDenied("Invalid file path")
if len(relative) > MAX_RELATIVE_LENGTH or "\x00" in relative:
raise CaptureDenied("Invalid file path")
if "\\" in relative or relative.startswith("/"):
if ("\\" in relative and os.sep == "\\") or relative.startswith("/"):
raise CaptureDenied("Invalid file path")
parts = relative.split("/")
for part in parts:
+21 -3
View File
@@ -32,12 +32,30 @@ def is_skipped_folder(name: str) -> bool:
return name == PREVIEW_FOLDER or is_trash_folder(name)
def in_trash_folder(relative: str) -> bool:
def path_separators(pathmod=os.path) -> str:
"""The characters that separate names in a root-relative path on this server.
``/`` always; ``\\`` only on Windows, where it cannot be part of a name. On
POSIX ``\\`` is an ordinary character (a Windows-style ``filename_prefix``
makes such a folder, #646).
"""
return "/\\" if pathmod.sep == "\\" else "/"
def split_relative(relative: str, pathmod=os.path) -> list[str]:
"""*relative* split into its names at this server's separators (#646)."""
if pathmod.sep == "\\":
relative = relative.replace("\\", "/")
return relative.split("/")
def in_trash_folder(relative: str, pathmod=os.path) -> bool:
"""Whether a root-relative file path lies in a trash folder (#543).
Takes either separator. Previews of it (``thumbnails/.Trash-1000/...``) count.
Takes this server's separators (#646). Previews of it
(``thumbnails/.Trash-1000/...``) count.
"""
folders = relative.replace("\\", "/").split("/")[:-1]
folders = split_relative(relative, pathmod)[:-1]
return any(is_trash_folder(part) for part in folders)
+8 -6
View File
@@ -2,11 +2,11 @@
This module provides comprehensive metadata extraction capabilities for
ComfyUI-generated images. It can extract workflow information, prompt data, and
generation parameters from PNG images that contain embedded ComfyUI metadata in
their text chunks.
generation parameters from the text chunks of PNG images and the EXIF records
ComfyUI writes for WebP, AVIF and JPEG images.
The extractor supports:
- Complete workflow data extraction from PNG text chunks
- Complete workflow data extraction from PNG text chunks and EXIF records
- Text encoder node identification and analysis
- Generation parameter extraction (steps, cfg_scale, sampler, etc.)
- Basic file information fallback when metadata is unavailable
@@ -36,6 +36,7 @@ import json
from typing import Optional, Dict, Any
from PIL import Image
from .exif_text import exif_text
from .logging_config import get_logger
from .png_text import png_text
@@ -89,9 +90,10 @@ class ComfyUIMetadataExtractor:
# Add basic file information
metadata["file_info"] = self.get_file_info(image_path, image)
# Extract ComfyUI-specific metadata from PNG text chunks,
# read without decoding the pixels (#523)
text = png_text(image)
# ComfyUI writes PNG text chunks, read without decoding the
# pixels (#523). WebP (and AVIF, once collected: #652) carry
# the same records as EXIF text, so those images link too.
text = png_text(image) or exif_text(image)
if text:
# Look for ComfyUI workflow data
if "workflow" in text:
+4 -1
View File
@@ -31,9 +31,12 @@ function descriptorScope(image) {
return image.root_scope;
}
/** #646: a POSIX server marks a path whose names hold a backslash; anywhere else a backslash stays refused. */
const backslashRefused = image => image.path.includes('\\') && image.path_style !== 'posix';
function validateIdentity(image) {
if (!object(image) || !Number.isSafeInteger(image.root_index) || image.root_index < 0 ||
typeof image.path !== 'string' || !image.path || image.path.includes('\\') || /^[a-z]:/i.test(image.path) || /[\x00-\x1f\x7f]/.test(image.path) ||
typeof image.path !== 'string' || !image.path || backslashRefused(image) || /^[a-z]:/i.test(image.path) || /[\x00-\x1f\x7f]/.test(image.path) ||
image.path.split('/').some(part => !part || part === '.' || part === '..')) throw new TypeError('Invalid inspection identity');
return descriptorScope(image);
}
+2
View File
@@ -73,6 +73,8 @@ const isDisabled = button => button.getAttribute('aria-disabled') === 'true';
export function imageOf(item) {
const target = item.target ?? {};
return { filename: item.filename, root_index: target.root_index, root_scope: target.root_scope, path: target.path,
// #646: a POSIX server's mark for a name holding a backslash, as the Images listing sends it.
...(target.path_style === 'posix' ? { path_style: 'posix' } : {}),
url: item.url, thumbnail_url: item.thumbnail_url ?? null, is_video: item.is_video === true,
media_type: item.is_video ? 'video' : 'image' };
}