The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(attachments): a file picked in the browser stays attached after uploads are cleaned up
emozilla15e8c1df0e30
diff --git a/tests/gateway/test_canonical_file_attach_staged_sources.py b/tests/gateway/test_canonical_file_attach_staged_sources.pyindex f21209fc2a8..ae7889b2eea 100644--- a/tests/gateway/test_canonical_file_attach_staged_sources.py+++ b/tests/gateway/test_canonical_file_attach_staged_sources.py@@ -11,6 +11,7 @@ import ioimport osfrom pathlib import Pathimport shutil+import timefrom types import SimpleNamespaceimport uuid@@ -158,3 +159,56 @@ async def test_an_upload_that_grew_past_the_browser_limit_is_not_copied(owner):os.truncate(receipt['path'], WEBAPP_ATTACHMENT_MAX_BYTES + 1)assert isinstance(await owner.attach(receipt), str) # refusedassert not owner.attachments.exists()+++@pytest_asyncio.fixture(params=['home-folder', 'profile-home'])+async def home_in_workspace(request, tmp_path, monkeypatch):+ """A chat whose workspace holds the profile home: the user's home folder (where sessions start+ unless ``terminal.cwd`` says otherwise; a default profile home is ``~/.hermes``) or the profile+ home itself."""+ from gateway.runtime_bootstrap import TicketStore+ from hermes_cli import install_identity++ monkeypatch.setattr(install_identity, '_INSTALL_ID_CACHE', {'root': None, 'value': None})+ home = tmp_path / '.hermes'+ home.mkdir()+ workspace = tmp_path if request.param == 'home-folder' else home+ authority = await _authority_with_old_desktop_chat(home, monkeypatch, cwd=workspace)+ host = _attach(authority, TicketStore('first', frozenset({authority.profile_id})), 'interactive', 'uid:1000')+ resumed = await host.dispatch({'id': 'resume', 'method': 'session.resume', 'params': {'session_id': 'old-desktop'}})+ assert 'result' in resumed, resumed++ def upload(payload):+ from hermes_cli.staged_uploads import publish_staged_upload, staged_upload_descriptor+ path = publish_staged_upload(io.BytesIO(payload), home, 'notes.txt')+ return staged_upload_descriptor(path, home)++ async def attach(params):+ reply = await host.dispatch({'id': 'attach', 'method': 'file.attach', 'params': {+ 'session_id': 'old-desktop', 'name': 'notes.txt', **params}})+ return reply.get('result') or reply.get('error', {}).get('message')++ return SimpleNamespace(home=home, upload=upload, attach=attach)++[email protected]('by', ['receipt', 'path'])+async def test_a_pick_in_a_workspace_holding_the_profile_home_outlives_upload_pruning(home_in_workspace, by):+ """A staged upload is a temporary copy the upload route prunes after 7 days, never a workspace+ file: a pick is copied into ``attachments/`` even when the session's workspace holds the profile+ home, so its ``@file:`` ref still names the file after the next upload prunes ``uploads/``. That+ holds for the receipt and for the staged path an install without an id attaches instead."""+ receipt = home_in_workspace.upload(b'what the user picked')+ params = {'staged_upload': receipt} if by == 'receipt' else {'path': receipt['path']}+ attached = await home_in_workspace.attach(params)+ assert isinstance(attached, dict) and attached['attached'] is True, attached+ stored = Path(attached['path'])+ assert attached['uploaded'] is True and stored.parent == (home_in_workspace.home / 'attachments').resolve(), attached++ # Eight days on, the user picks another file in the browser: the upload prunes stale picks.+ week_ago = time.time() - 8 * 24 * 60 * 60+ os.utime(receipt['path'], (week_ago, week_ago))+ home_in_workspace.upload(b'another pick')++ assert not Path(receipt['path']).exists()+ assert stored.read_bytes() == b'what the user picked'diff --git a/tui_gateway/prompt_attachments.py b/tui_gateway/prompt_attachments.pyindex ef606e17682..e6b7c0560bf 100644--- a/tui_gateway/prompt_attachments.py+++ b/tui_gateway/prompt_attachments.py@@ -232,19 +232,36 @@ def _stage_browser_file_attachment(session: dict, staged_upload: object, name: sraw_home, raw_path = parse_staged_upload(staged_upload)source = resolve_staged_upload(Path(raw_home), raw_path)- # Keep the existing out-of-workspace copy into attachments/, which is visible to- # container/SSH terminal backends through cache mounts.+ # Copied into attachments/ even inside the workspace: the upload route prunes its staging after+ # 7 days. attachments/ is also visible to container/SSH terminal backends through cache mounts.return _stage_session_file_attachment(- session, raw_path=str(source), data_url="", name=name, max_bytes=WEBAPP_ATTACHMENT_MAX_BYTES)+ session, raw_path=str(source), data_url="", name=name, max_bytes=WEBAPP_ATTACHMENT_MAX_BYTES,+ staged=True)+++def _referenced_in_place(session: dict, path: Path, workspace: Path, *, staged: bool) -> bool:+ """Whether an attached host file is referenced where it is: inside the workspace, and not a+ browser upload staged in the profile's ``uploads/`` (pruned after 7 days, so always copied)."""+ if staged or not path.is_relative_to(workspace):+ return False+ try:+ from hermes_cli.staged_uploads import is_staged_upload+ except ImportError:+ # An install without the web stack (fastapi) has no upload route that could stage one.+ return True+ profile_home = session.get("profile_home")+ return not is_staged_upload(Path(profile_home) if profile_home else _hermes_home, path)def _stage_session_file_attachment(session: dict, *, raw_path: str, data_url: str, name: str, max_bytes: int | None = None,+ staged: bool = False,) -> tuple[Path, bool]:"""Make a desktop file attachment available to the gateway agent: ``(stored_path, uploaded)``.Inside the workspace -> as-is; gateway-visible but outside -> copied into ``attachments/``(bind-mounted into container backends so ``@file:`` resolves in the sandbox); not on the- gateway -> ``data_url`` bytes decoded into ``attachments/``. ``max_bytes`` caps the copy of a+ gateway -> ``data_url`` bytes decoded into ``attachments/``. A browser upload (*staged*, or a+ path in the profile's ``uploads/``) is always copied. ``max_bytes`` caps the copy of abrowser upload; a host file is copied whatever its size, inline bytes up to``_ATTACHMENT_MAX_BYTES``."""workspace = Path(_session_cwd(session)).resolve()@@ -263,13 +280,11 @@ def _stage_session_file_attachment(found = _resolve_attachment_path(path_token)resolved = Path(found).resolve() if found is not None else Noneif resolved is not None:- try:- resolved.relative_to(workspace)+ if _referenced_in_place(session, resolved, workspace, staged=staged):return resolved, False- except ValueError:- # Without a cap the copy below streams the file, so its size never reaches memory.- payload = None if max_bytes is None else _read_attachment_bytes(resolved, max_bytes)- filename = resolved.name+ # Without a cap the copy below streams the file, so its size never reaches memory.+ payload = None if max_bytes is None else _read_attachment_bytes(resolved, max_bytes)+ filename = resolved.nameelse:if not data_url:raise ValueError("file not found on gateway and no data_url provided")