Skip to content

The agent that grows with you

fix(acp): an un-acked image prompt's retry reuses its staging, never re-fetches

Teknium03be2bbdfe2d
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index 2424184c338..9d621a3ed28 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -123,14 +123,16 @@ def _slash_command(text):
return command.name if command is not None else None
-def _submit_fingerprint(session_id, text, attachments):
- """Content identity of one logical prompt: its text and the staged image bytes (staging names
- are disposable; the authority reconciles a retry by the same digests)."""
+def _submit_fingerprint(session_id, content):
+ """Identity of one logical prompt as the editor sent it (text, image ``data:`` bytes, remote image
+ URLs), taken before staging: a retry of the same prompt matches without re-fetching a remote image,
+ whose second download could fail or return other bytes and so change what is submitted."""
import hashlib
- digest = hashlib.sha256(text.encode())
- for item in attachments:
- with open(item['path'], 'rb') as staged:
- digest.update(item['mime'].encode() + b'\0' + hashlib.sha256(staged.read()).digest())
+ digest = hashlib.sha256()
+ for part in [content] if isinstance(content, str) else content:
+ kind, value = ('text', part) if isinstance(part, str) else \
+ ('text', part['text']) if part.get('type') == 'text' else ('image', part['image_url']['url'])
+ digest.update(kind.encode() + len(value).to_bytes(8, 'big') + value.encode())
return session_id, digest.hexdigest()
@@ -613,12 +615,20 @@ class GatewayACPAgent(acp.Agent):
raise GatewayClientError(self._unknown_recovery(session_id, submitted=False))
from acp_adapter.content import _content_blocks_to_openai_user_content
content = _content_blocks_to_openai_user_content(prompt)
- # Only a remote image fetch leaves the loop; every other prompt stages inline, as before.
- text, attachments = (await asyncio.to_thread(_stage_user_content, content)) if _has_remote_image(content) \
- else _stage_user_content(content)
+ retry_key = _submit_fingerprint(session_id, content)
+ # The editor's retry of an un-acked submit resends what the owner may already hold: the staged
+ # content and input_id are reused, never prepared (a remote image fetched) a second time.
# Only this session's very next prompt may be the editor's retry of an un-acked submit; any
# prompt (slash work included) retires the retained identity, so a later repeat is new work.
retained = self._unacked.pop(session_id, None)
+ reused = retained if retained is not None and retained[0] == retry_key else None
+ if reused is not None:
+ staged = reused[2]
+ else:
+ # Only a remote image fetch leaves the loop; every other prompt stages inline, as before.
+ staged = (await asyncio.to_thread(_stage_user_content, content)) \
+ if _has_remote_image(content) else _stage_user_content(content)
+ text, attachments = staged
command = _slash_command(text) if not attachments else None
if command is not None:
from acp_adapter.gateway_commands import run_command
@@ -633,8 +643,7 @@ class GatewayACPAgent(acp.Agent):
submit = {'text': text}
if attachments:
submit['attachments'] = attachments
- retry_key = await asyncio.to_thread(_submit_fingerprint, session_id, text, attachments)
- input_id = retained[1] if retained is not None and retained[0] == retry_key else uuid.uuid4().hex
+ input_id = reused[1] if reused is not None else uuid.uuid4().hex
self._submitting.add(session_id)
try:
# Inside the try: a failed reconnect is as ambiguous for a retained identity as a lost ack.
@@ -646,7 +655,7 @@ class GatewayACPAgent(acp.Agent):
if not isinstance(exc, GatewayRPCError):
# Transport loss, timeout or cancel before the ack: the owner may hold this admission.
# Keep its identity for the editor's retry of the same prompt (latest 64 sessions).
- self._unacked[session_id] = (retry_key, input_id)
+ self._unacked[session_id] = (retry_key, input_id, staged)
while len(self._unacked) > 64:
self._unacked.pop(next(iter(self._unacked)))
self._pending_cancels.discard(session_id)
diff --git a/tests/acp_adapter/test_gateway_remote_image_submit.py b/tests/acp_adapter/test_gateway_remote_image_submit.py
new file mode 100644
index 00000000000..bb2e2d5a4f0
--- /dev/null
+++ b/tests/acp_adapter/test_gateway_remote_image_submit.py
@@ -0,0 +1,85 @@
+"""A remote image URL is fetched once per logical prompt: an un-acked submit's retry reuses what the first
+attempt staged (never a re-download that could change the content and so the input_id), and the editor's
+Stop during the download keeps the prompt from being submitted at all (Greptile review on #140188)."""
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import pytest
+from acp.schema import ImageContentBlock, TextContentBlock
+
+from acp_adapter.gateway_server import GatewayACPAgent
+from hermes_cli.gateway_client import GatewayClientError
+from tests.acp_adapter.test_gateway_prompt_content import _ONE_PX_PNG, _allow_loopback
+
+
+def host():
+ """Loopback image host: the first GET of /pic serves a PNG, later ones 404 (a flaky or changed URL).
+ ``gate`` (when set) holds every response until released (a slow download)."""
+ state = {'hits': 0, 'gate': None, 'started': threading.Event()}
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ state['started'].set()
+ if state['gate'] is not None:
+ state['gate'].wait(10)
+ state['hits'] += 1
+ ok = state['hits'] == 1
+ body = _ONE_PX_PNG if ok else b'gone'
+ self.send_response(200 if ok else 404)
+ self.send_header('Content-Type', 'image/png' if ok else 'text/plain')
+ self.send_header('Content-Length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ state['url'] = f'http://127.0.0.1:{server.server_port}/pic'
+ try:
+ yield state
+ finally:
+ if state['gate'] is not None:
+ state['gate'].set()
+ server.shutdown()
+ server.server_close()
+
+
+class _LosesFirstAck:
+ """The owner admits the first submit but its reply is lost (transport failure, not an RPC refusal)."""
+
+ def __init__(self, agent):
+ self.agent, self.calls = agent, []
+
+ async def rpc(self, method, **params):
+ self.calls.append((method, params))
+ if len(self.calls) == 1:
+ raise GatewayClientError('Gateway disconnected; turn outcome is unknown.')
+ self.agent._terminals['adm-1'] = {}
+ return {'admission_id': 'adm-1'}
+
+
+def _prompt(url):
+ return [TextContentBlock(type='text', text='describe'),
+ ImageContentBlock(type='image', data='', uri=url, mimeType='image/png')]
+
+
+async def test_unacked_remote_image_retry_reuses_the_first_staging(tmp_path, monkeypatch, host):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ _allow_loopback(monkeypatch, True)
+ agent = GatewayACPAgent()
+ agent._gateway = _LosesFirstAck(agent)
+ agent._snapshots['s'] = {}
+ with pytest.raises(GatewayClientError, match='outcome is unknown'):
+ await agent.prompt(_prompt(host['url']), 's')
+ await agent.prompt(_prompt(host['url']), 's')
+ (_, first), (_, retry) = agent._gateway.calls
+ # A second download would 404 and turn the image into URL text, a different prompt and a new input_id.
+ assert host['hits'] == 1
+ assert retry['input_id'] == first['input_id']
+ assert retry['text'] == first['text'] == 'describe'
+ assert retry['attachments'] == first['attachments']
+