Skip to content

The agent that grows with you

fix(google_meet): say-queue appends survive the speaker's rewrite

Maciej Lisiewskid5442d0a47a1
diff --git a/plugins/google_meet/_jsonfile.py b/plugins/google_meet/_jsonfile.py
index b1d224fa260..0da976005c1 100644
--- a/plugins/google_meet/_jsonfile.py
+++ b/plugins/google_meet/_jsonfile.py
@@ -1,10 +1,14 @@
-"""Tiny JSON read helper shared by the bot, process manager, node registry and node server."""
+"""Tiny JSON file helpers shared by the bot, process manager, node registry and node server."""
from __future__ import annotations
import json
+import threading
+from contextlib import contextmanager
from pathlib import Path
-from typing import Any, Optional
+from typing import Any, Iterator, Optional
+
+_say_queue_lock_holder = threading.local()
def read_json(path: Path) -> Optional[Any]:
@@ -15,3 +19,14 @@ def read_json(path: Path) -> Optional[Any]:
return json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return None
+
+
+@contextmanager
+def say_queue_lock(queue_path: Path) -> Iterator[None]:
+ """Cross-process lock around ``say_queue.jsonl`` edits. The bot's speaker re-reads and rewrites the
+ queue to drop what it spoke; an agent-side append landing in between would be wiped by the rewrite."""
+ from hermes_cli.auth import _file_lock
+
+ lock_path = queue_path.with_name(queue_path.name + ".lock")
+ with _file_lock(lock_path, _say_queue_lock_holder, 10.0, f"Timed out waiting for say queue lock ({lock_path})"):
+ yield
diff --git a/plugins/google_meet/node/server.py b/plugins/google_meet/node/server.py
index 4017690b8db..06ae54d8042 100644
--- a/plugins/google_meet/node/server.py
+++ b/plugins/google_meet/node/server.py
@@ -17,7 +17,7 @@ from pathlib import Path
from typing import Any, Dict, Optional
from hermes_constants import get_hermes_home
-from plugins.google_meet._jsonfile import read_json
+from plugins.google_meet._jsonfile import read_json, say_queue_lock
from utils import atomic_json_write
from plugins.google_meet.node import protocol as _proto
@@ -45,7 +45,7 @@ def _rpc_say(payload: dict[str, Any], pm) -> dict[str, Any]:
with contextlib.suppress(OSError):
queue = Path(active["out_dir"]) / "say_queue.jsonl"
queue.parent.mkdir(parents=True, exist_ok=True)
- with queue.open("a", encoding="utf-8") as fh:
+ with say_queue_lock(queue), queue.open("a", encoding="utf-8") as fh:
fh.write(json.dumps({"text": text, "ts": time.time()}) + "\n")
enqueued = True
return {"ok": True, "enqueued": enqueued, "text": text}
diff --git a/plugins/google_meet/process_manager.py b/plugins/google_meet/process_manager.py
index c2bb084edaa..984901d7a7b 100644
--- a/plugins/google_meet/process_manager.py
+++ b/plugins/google_meet/process_manager.py
@@ -20,6 +20,7 @@ from pathlib import Path
from typing import Any, Dict, Optional
from hermes_constants import get_hermes_home
+from plugins.google_meet._jsonfile import say_queue_lock
from utils import atomic_json_write
@@ -174,7 +175,7 @@ def enqueue_say(text: str) -> dict[str, Any]:
return {"ok": False, "reason": f"out_dir missing: {out_dir}"}
queue_path = out_dir / "say_queue.jsonl"
entry = {"id": uuid.uuid4().hex[:12], "text": text}
- with queue_path.open("a", encoding="utf-8") as f:
+ with say_queue_lock(queue_path), queue_path.open("a", encoding="utf-8") as f:
f.write(json.dumps(entry) + "\n")
return {"ok": True, "meetingId": active.get("meeting_id"), "enqueued_id": entry["id"],
"queue_path": str(queue_path)}
diff --git a/plugins/google_meet/realtime/openai_client.py b/plugins/google_meet/realtime/openai_client.py
index a4b9ed7ef59..13442731b32 100644
--- a/plugins/google_meet/realtime/openai_client.py
+++ b/plugins/google_meet/realtime/openai_client.py
@@ -15,6 +15,8 @@ import uuid
from pathlib import Path
from typing import Any, Callable, Optional
+from plugins.google_meet._jsonfile import say_queue_lock
+
REALTIME_URL = "wss://api.openai.com/v1/realtime"
@@ -187,7 +189,9 @@ class RealtimeSpeaker:
except Exception as exc:
result = {"ok": False, "error": str(exc)}
self._append_processed(head, result)
- # Re-read (new entries may have arrived), then drop the head by position or id.
- latest = self._read_queue()
- self._rewrite_queue(latest[1:] if latest and latest[0].get("id") == head.get("id")
- else [e for e in latest if e.get("id") != head.get("id")])
+ # Re-read (new entries may have arrived), then drop the head by position or id — under the
+ # queue lock, so a meet_say append cannot land between the re-read and the rewrite.
+ with say_queue_lock(self.queue_path):
+ latest = self._read_queue()
+ self._rewrite_queue(latest[1:] if latest and latest[0].get("id") == head.get("id")
+ else [e for e in latest if e.get("id") != head.get("id")])
diff --git a/tests/plugins/test_google_meet_realtime.py b/tests/plugins/test_google_meet_realtime.py
index 1c0b749191a..8cfb784f9e2 100644
--- a/tests/plugins/test_google_meet_realtime.py
+++ b/tests/plugins/test_google_meet_realtime.py
@@ -225,3 +225,53 @@ def test_speaker_run_until_stopped_processes_queue(tmp_path):
assert queue.read_text().strip() == ""
+
+
+def test_speaker_drain_keeps_a_say_enqueued_during_the_rewrite(tmp_path, monkeypatch):
+ """A meet_say append landing between the speaker's post-speak re-read and its queue rewrite must
+ survive the rewrite and be spoken (it was reported "enqueued" to the agent)."""
+ import threading
+
+ from plugins.google_meet import process_manager as pm
+ from plugins.google_meet.realtime.openai_client import RealtimeSpeaker
+ from tests.lock_contention import watch_file_lock_contention
+ from tests.waiting import wait_until
+
+ contended = watch_file_lock_contention(monkeypatch)
+
+ queue = tmp_path / "say_queue.jsonl"
+ queue.write_text(json.dumps({"id": "a", "text": "first"}) + "\n")
+ pm._write_active({"pid": 0, "meeting_id": "abc-defg-hij", "out_dir": str(tmp_path), "mode": "realtime",
+ "url": "https://meet.google.com/abc-defg-hij", "started_at": 0})
+ stub = _StubSession()
+ speaker = RealtimeSpeaker(stub, queue_path=queue)
+ real_read = speaker._read_queue
+ reads = {"n": 0}
+ appended = threading.Event()
+ peers: list[threading.Thread] = []
+
+ def read_then_peer_appends():
+ out = real_read()
+ reads["n"] += 1
+ if reads["n"] == 2:
+ # The post-speak re-read: the agent process enqueues right after it, before the rewrite.
+ peer = threading.Thread(target=lambda: (pm.enqueue_say("second"), appended.set()), daemon=True)
+ peer.start()
+ peers.append(peer)
+ # Unserialized, the append lands now; serialized, it is seen blocking on the queue lock.
+ wait_until(lambda: appended.is_set() or contended.is_set(),
+ what="the append landed or blocked on the say-queue lock")
+ return out
+
+ speaker._read_queue = read_then_peer_appends
+
+ def _stop():
+ # Done once both are spoken, or once the peer's append has settled and nothing is left to speak.
+ if len(stub.spoken) >= 2:
+ return True
+ return bool(peers) and not peers[0].is_alive() and not real_read()
+
+ speaker.run_until_stopped(_stop, poll_interval=0.01)
+ for peer in peers:
+ peer.join(10)
+ assert stub.spoken == ["first", "second"]