Compare commits

...
Author SHA1 Message Date
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
37 changed files with 486 additions and 50 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.
+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)
+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.0"
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');
});
@@ -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",
):
+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()
+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))
+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)
+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)
+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' };
}