Skip to content

The agent that grows with you

fix(tui_gateway): extend atomic xb allocation to attached images and bound cleanup exception

webtecnicab4faf6587e90
diff --git a/tests/tui_gateway/test_file_attachment_allocation.py b/tests/tui_gateway/test_file_attachment_allocation.py
index f8a301b0944..225585d7e7a 100644
--- a/tests/tui_gateway/test_file_attachment_allocation.py
+++ b/tests/tui_gateway/test_file_attachment_allocation.py
@@ -118,3 +118,21 @@ def test_failed_write_removes_only_its_partial_upload(sessions, tmp_path, monkey
survivor = Path(success["result"]["path"])
assert survivor.read_bytes() == b"complete upload"
assert set(root.iterdir()) == {survivor}
+
+
+def test_cross_session_attached_images_allocate_unique_paths(sessions, tmp_path):
+ session_a = sessions["first"]
+ session_b = sessions["second"]
+ img_bytes_a = b"SESSION_A_IMAGE_PNG"
+ img_bytes_b = b"SESSION_B_IMAGE_PNG"
+
+ path_a = server._queue_attached_image(session_a, img_bytes_a, ".png", prefix="upload")
+ # Reset image_counter in session_b to 0 to simulate concurrent/fresh session in same profile
+ session_b["image_counter"] = 0
+ path_b = server._queue_attached_image(session_b, img_bytes_b, ".png", prefix="upload")
+
+ assert path_a != path_b
+ assert path_a.read_bytes() == img_bytes_a
+ assert path_b.read_bytes() == img_bytes_b
+ assert path_a.exists() and path_b.exists()
+
diff --git a/tui_gateway/prompt_attachments.py b/tui_gateway/prompt_attachments.py
index df845f25abf..5c612ee82cc 100644
--- a/tui_gateway/prompt_attachments.py
+++ b/tui_gateway/prompt_attachments.py
@@ -136,18 +136,27 @@ def _session_images_dir(session: dict) -> Path:
def _queue_attached_image(session: dict, img_bytes: bytes, ext: str, *, prefix: str) -> Path:
"""Write image bytes into the session images dir and queue them for the next submit."""
- session["image_counter"] = session.get("image_counter", 0) + 1
img_dir = _session_images_dir(session)
img_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
- img_path = img_dir / f"{prefix}_{ts}_{session['image_counter']}{ext}"
+ counter = session.get("image_counter", 0) + 1
+ while True:
+ candidate = img_dir / f"{prefix}_{ts}_{counter}{ext}"
+ try:
+ upload = candidate.open("xb")
+ except FileExistsError:
+ counter += 1
+ else:
+ break
+ session["image_counter"] = counter
try:
- img_path.write_bytes(img_bytes)
+ with upload:
+ upload.write(img_bytes)
except Exception:
- session["image_counter"] = max(0, session["image_counter"] - 1)
+ candidate.unlink(missing_ok=True)
raise
- session.setdefault("attached_images", []).append(str(img_path))
- return img_path
+ session.setdefault("attached_images", []).append(str(candidate))
+ return candidate
def _format_ref_value(value: str) -> str:
@@ -233,7 +242,7 @@ def _stage_session_file_attachment(
try:
with upload:
upload.write(payload)
- except BaseException:
+ except Exception:
target.unlink(missing_ok=True)
raise
return target.resolve(), True