feat(pheby): add authenticated GPT-Live voice setup

Use Hermes to exchange WebRTC offers for the connector profile. Keep cancellation acknowledgments private and guard replacement runs against stale delivery.
This commit is contained in:
Chris Mendoza
2026-11-20 12:36:28 -05:00
parent 3bfb300a2f
commit 49b180922d
8 changed files with 462 additions and 72 deletions
+46
View File
@@ -1155,6 +1155,24 @@ class TestBridge:
ok = await hb.cancel_run("convY", "wrong-run")
assert ok is False
@pytest.mark.asyncio
async def test_cancel_ack_is_private_and_terminal_event_is_broadcast(self, tmp_path):
server = make_server(tmp_path)
caller, other = FakeClientConnection(), FakeClientConnection()
caller.authenticated = other.authenticated = True
server._clients.update(caller=caller, other=other)
server.adapter.gateway_runner = runner = FakeRunner()
runner._running_agents["agent:main:pheby:dm:voice-chat"] = FakeAgent()
from pheby import hermes_bridge as hb
hb._ACTIVE_RUNS["voice-chat"] = {"run_id": "voice-run", "started": 0}
await server._handle_run_cancel(caller, {"conversation_id": "voice-chat", "run_id": "voice-run"}, "r1")
event = {"type": "run.finished", "conversation_id": "voice-chat", "run_id": "voice-run", "status": "cancelled"}
assert caller.ws.events() == [{**event, "request_id": "r1"}, event]
assert other.ws.events() == [event]
assert hb.active_run_id("voice-chat") is None
@pytest.mark.asyncio
async def test_reasoning_set_validation(self, tmp_path):
from pheby import hermes_bridge as hb
@@ -1404,6 +1422,34 @@ class TestAdapterUnits:
assert [e["type"] for e in client.ws.events()][-2:] == [
proto.S_MESSAGE_COMPLETE, proto.S_RUN_FINISHED]
@pytest.mark.asyncio
async def test_cancelled_task_delivery_does_not_finish_successor(self, tmp_path, monkeypatch):
from gateway.config import PlatformConfig
from gateway.platforms.base import BasePlatformAdapter
from pheby import hermes_bridge as hb
server = make_server(tmp_path)
listener = FakeClientConnection()
listener.authenticated = True
server._clients["listener"] = listener
adapter = PhebyAdapter(PlatformConfig(enabled=True))
adapter._server = server
conv = "voice-replacement"
adapter._drafts[conv] = {"run_id": "new", "message_id": "draft-new", "text": ""}
monkeypatch.setitem(hb._ACTIVE_RUNS, conv, {"run_id": "new", "started": 0})
async def late_delivery(self, event, key):
await self.send(conv, "old final")
await self.edit_message(conv, "draft-old", "old edit", finalize=True)
monkeypatch.setattr(BasePlatformAdapter, "_process_message_background", late_delivery)
event = SimpleNamespace(metadata={"pheby_run_id": "old"}, source=SimpleNamespace(chat_id=conv))
await adapter._process_message_background(event, "session-key")
assert hb.active_run_id(conv) == "new"
assert adapter._drafts[conv]["message_id"] == "draft-new"
assert listener.ws.events() == []
def test_transport_auth_is_gateway_authorization(self):
from pheby.adapter import PhebyAdapter
from gateway.config import PlatformConfig
+117
View File
@@ -0,0 +1,117 @@
import aiohttp
import pytest
from pheby import voice_live
from test_pheby import FakeClientConnection, make_server
@pytest.mark.asyncio
async def test_session_uses_hermes_client_delegation_and_owning_profile(tmp_path, monkeypatch):
import io
import json
from types import SimpleNamespace
from tools import voice_live as upstream
home = tmp_path / "voice-profile"
home.mkdir()
(home / ".env").write_text("OPENAI_API_KEY=profile-test-key\n")
adapter = SimpleNamespace(hermes_home=home)
def exchange(request, timeout):
assert request.full_url == "https://api.openai.com/v1/live/sessions"
assert request.get_header("Authorization") == "Bearer profile-test-key"
body = json.loads(request.data)
assert body["session"]["delegation"] == {"type": "client"}
assert body["session"]["instructions"] == upstream.LIVE_PERSONA
assert body["transport"] == {"type": "webrtc", "sdp": "offer\r\n"}
return io.BytesIO(b'{"session":{"id":"live-test"},"transport":{"sdp":"answer"}}')
monkeypatch.setattr(upstream.urllib.request, "urlopen", exchange)
assert (await voice_live.status(adapter))["available"] is True
assert await voice_live.create_session(adapter, "offer\r\n") == {"session_id": "live-test", "sdp": "answer"}
@pytest.mark.asyncio
async def test_voice_routes_authenticate_and_preserve_the_sdp_offer(tmp_path, monkeypatch):
server = make_server(tmp_path)
server.config.port = 0
offers = []
async def status(adapter):
return {"available": True, "model": "gpt-live-1"}
async def create_session(adapter, offer):
offers.append(offer)
return {"session_id": "live-id", "sdp": "answer\r\n"}
monkeypatch.setattr(voice_live, "status", status)
monkeypatch.setattr(voice_live, "create_session", create_session)
assert await server.start()
try:
port = server._site._server.sockets[0].getsockname()[1]
root = f"http://127.0.0.1:{port}/voice-live"
auth = {"Authorization": f"Bearer {server.config.secret}"}
async with aiohttp.ClientSession() as http:
async with http.get(root + "/status") as response:
assert response.status == 401
async with http.get(root + "/status", headers=auth) as response:
assert (await response.json())["available"] is True
async with http.post(root + "/session", json={"sdp": "offer"}) as response:
assert response.status == 401
async with http.post(root + "/session", headers=auth, json={"sdp": " "}) as response:
assert response.status == 400
async with http.post(root + "/session", headers=auth, json={"sdp": "x" * 65_536}) as response:
assert response.status == 413
async with http.post(root + "/session", headers=auth, json={"sdp": "offer\r\n"}) as response:
assert response.status == 200
assert response.headers["Cache-Control"] == "no-store"
assert await response.json() == {"session_id": "live-id", "sdp": "answer\r\n"}
assert offers == ["offer\r\n"]
finally:
await server.stop()
@pytest.mark.asyncio
async def test_voice_turn_history_uses_the_current_hermes_store(tmp_path):
from types import SimpleNamespace
from persistence.conversation.messages import NewMessage
from persistence.conversation.sessions import NewSession
from persistence_assembly import open_persistence, profile_scope
from pheby import hermes_bridge as bridge
server = make_server(tmp_path)
conversation = "shared-thread"
key = bridge._session_key_for(conversation)
with open_persistence(profile_scope()) as db:
server.adapter.gateway_runner = SimpleNamespace(_session_db=db)
await server.router.ensure_conversation(conversation)
for sid, text in [("prior", "Typed first"), ("current", "Spoken next")]:
db.sessions.create(NewSession(session_id=sid, source="pheby", session_key=key, chat_id=conversation))
db.messages.append(sid, NewMessage(role="user", content=text))
await bridge.persist_cron_delivery(conversation, "Scheduled note", {"job_id": "test"})
messages, found, more = await bridge.conversation_history(conversation, 10)
assert found and not more
assert [item["text"] for item in messages] == ["Typed first", "Spoken next", "Scheduled note"]
@pytest.mark.asyncio
async def test_voice_correction_uses_the_existing_chat_and_displays_only_the_utterance(tmp_path, monkeypatch):
from pheby import hermes_bridge as bridge
server = make_server(tmp_path)
client = FakeClientConnection()
conversation = "correction-thread"
monkeypatch.setattr(bridge, "_ACTIVE_RUNS", {})
await server._handle_chat_send(client, {
"conversation_id": conversation, "text": "Thursday instead.",
"voice_context": "Find a train for Friday.",
}, "correction")
event = server.adapter.handled[-1]
assert event.source.chat_id == conversation
assert bridge._display_user_text(event.text) == "Thursday instead."
assert "Earlier spoken request that was interrupted: Find a train for Friday." in event.text
assert client.ws.events()[0]["type"] == "run.accepted"