Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(realtime)!: remove the experimental Codex subscription realtime adapter

rubenluetke10-beep29c736559e62
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.py
index 575a4d8b5d..5a7f47c07c 100644
--- a/jarvis/brain/model_catalog.py
+++ b/jarvis/brain/model_catalog.py
@@ -488,14 +488,11 @@ TTS_CATALOG: dict[str, tuple[str, list[ModelInfo]]] = {
# they target dedicated translation/transcription sessions, not the general
# duplex voice-agent protocol implemented by this adapter.
REALTIME_MODELS: dict[str, list[ModelInfo]] = {
- # ChatGPT-Live (Codex v3): the SERVER chooses the model — a client
- # `session.model` is rejected outright, and the old v1 protocol (which
- # accepted a model) answers 403 since the ChatGPT-Live launch (both
- # verified live 2026-08-01). One honest entry instead of a fake choice;
- # model selection lives on the metered OpenAI Realtime card.
- "codex-subscription-realtime": _curated(
- [("auto", "ChatGPT-Live (model chosen by OpenAI)")]
- ),
+ # codex-subscription-realtime was REMOVED 2026-08-10 together with its
+ # adapter: Codex's experimental app-server realtime surface never held a
+ # dependable call. Subscription voice continues over the classic pipeline
+ # (voice.profile = "codex-subscription-voice"), which needs no realtime
+ # model catalog entry.
# local-realtime: the served model is whatever its operator loaded, so the
# only honest curated entry is "ask the server". The adapter resolves it
# through /v1/models at connect time (same as the local brain card), and a
@@ -543,22 +540,6 @@ REALTIME_MODELS: dict[str, list[ModelInfo]] = {
# gemini-live: verified 2026-07-10 against the Live API capabilities guide,
# which now permits the complete 30-voice Gemini prebuilt roster.
REALTIME_VOICES: dict[str, list[ModelInfo]] = {
- # Codex app-server ChatGPT-Live v3 voices. ``cove`` is the v3 default, so it
- # leads the picker just as each realtime model catalog leads with its
- # adapter default.
- "codex-subscription-realtime": _ids(
- [
- "cove",
- "juniper",
- "maple",
- "spruce",
- "ember",
- "vale",
- "breeze",
- "arbor",
- "sol",
- ]
- ),
# A self-hosted server ships whatever voices its operator installed, and a
# list of OpenAI voice names would be a guess the server then rejects. One
# honest entry: the adapter sends no voice override and the server uses its
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 56574696b4..cbc5c1adf1 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -3951,24 +3951,24 @@ _LEGACY_CODEX_REALTIME_HEALED: set[Path] = set()
def _heal_legacy_codex_realtime_once(path: Path) -> None:
- """Retire the Pipeline profile accidentally persisted by old Realtime UI."""
+ """Route a removed Codex Realtime selection onto the stable composition."""
if path in _LEGACY_CODEX_REALTIME_HEALED:
return
_LEGACY_CODEX_REALTIME_HEALED.add(path)
try:
- from jarvis.core.config_writer import migrate_legacy_codex_realtime_selection
+ from jarvis.core.config_writer import migrate_removed_codex_realtime_provider
- migrated = migrate_legacy_codex_realtime_selection(path=path)
+ migrated = migrate_removed_codex_realtime_provider(path=path)
except Exception: # noqa: BLE001 - a boot migration must not block startup
logging.getLogger(__name__).warning(
- "Could not repair the legacy Codex Realtime voice selection.",
+ "Could not migrate the removed Codex Realtime voice selection.",
exc_info=True,
)
return
if migrated:
logging.getLogger(__name__).warning(
- "Repaired legacy Codex Realtime configuration: removed the "
- "Pipeline-only voice profile and restored Realtime mode."
+ "Migrated the removed codex-subscription-realtime selection to "
+ "the stable ChatGPT subscription voice profile (Pipeline mode)."
)
@@ -4007,9 +4007,9 @@ def load_config(
"""
if config_file is None:
config_file = resolve_config_path()
- # An earlier Codex-subscription implementation silently rewrote the
- # Realtime selection as a Pipeline profile. Heal the exact persisted
- # triple before the first parse so the UI and runtime see one state.
+ # The codex-subscription-realtime adapter was removed 2026-08-10. A
+ # config still pinning it is routed onto the stable subscription
+ # profile before the first parse so the UI and runtime see one state.
_heal_legacy_codex_realtime_once(config_file)
# One-time dictation-shortcut backfill BEFORE the file is read, so the
# very first boot after the update already sees the healed values
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 9d71d3f679..d10159e2cf 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -1301,17 +1301,20 @@ def set_realtime_voice_selection(
_atomic_write(path, out)
-def migrate_legacy_codex_realtime_selection(
+def migrate_removed_codex_realtime_provider(
*, path: Path = DEFAULT_CONFIG_FILE
) -> bool:
- """Repair the exact Realtime-to-Pipeline state written by the old switch.
-
- Older builds represented the Codex Realtime card as the classic
- ``codex-subscription-voice`` profile and persisted Pipeline mode. The card
- then appeared active while the Realtime mode control refused to switch,
- leaving no in-app recovery path. Only that exact three-key legacy state is
- changed; explicit Pipeline configurations using any other provider remain
- untouched.
+ """Route a removed Codex Realtime selection onto the stable composition.
+
+ The ``codex-subscription-realtime`` adapter was removed 2026-08-10 (the
+ experimental Codex app-server realtime surface never held a dependable
+ call). A config still pinning it would boot into Realtime mode with no
+ resolvable provider and silently lose subscription voice. Instead, the
+ pin is cleared from every explicit slot and — when it was the PRIMARY
+ selection — the install lands on the classic subscription composition
+ (``voice.profile = "codex-subscription-voice"``, Pipeline mode), which
+ keeps voice on the same ChatGPT login. Configs not naming the removed
+ provider are never touched.
"""
if path == DEFAULT_CONFIG_FILE:
from jarvis.core.config import resolve_config_path
@@ -1320,6 +1323,7 @@ def migrate_legacy_codex_realtime_selection(
if not path.exists():
return False
+ removed = "codex-subscription-realtime"
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
@@ -1328,20 +1332,27 @@ def migrate_legacy_codex_realtime_selection(
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
realtime = brain.get("realtime") if brain is not None else None
- voice = doc.get("voice")
- if (
- realtime is None
- or voice is None
- or str(realtime.get("provider") or "").strip()
- != "codex-subscription-realtime"
- or str(voice.get("profile") or "").strip()
- != "codex-subscription-voice"
- or str(voice.get("mode") or "").strip().lower() != "pipeline"
- ):
+ if realtime is None:
+ return False
+ slots = ("provider", "fallback_provider", "fallback_provider_2")
+ pinned = [
+ slot
+ for slot in slots
+ if str(realtime.get(slot) or "").strip() == removed
+ ]
+ if not pinned:
return False
- voice["profile"] = ""
- voice["mode"] = "realtime"
+ was_primary = "provider" in pinned
+ for slot in pinned:
+ realtime[slot] = ""
+ if was_primary:
+ voice = doc.get("voice")
+ if voice is None:
+ voice = tomlkit.table()
+ doc["voice"] = voice
+ voice["profile"] = "codex-subscription-voice"
+ voice["mode"] = "pipeline"
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 475c7d05f9..5d27ab52aa 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -23,8 +23,6 @@ import inspect
import logging
import threading
import time
-from collections.abc import Mapping
-from types import SimpleNamespace
from typing import Any, Final, Literal, get_args
from fastapi import APIRouter, HTTPException, Request, Response
@@ -470,8 +468,6 @@ def _spec_to_payload(
active_computer_use: str | None = None,
active_dictation: str | None = None,
local_model_override: str | None = None,
- codex_subscription_ready: bool | None = None,
- codex_subscription_status: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
if spec.tier == "brain":
active = spec.id == active_brain
@@ -516,32 +512,7 @@ def _spec_to_payload(
}
codex_status = None
if spec.auth_mode == "codex":
- from_isolated_snapshot = (
- spec.id == "codex-subscription-realtime" and codex_subscription_status is not None
- )
- codex_status = (
- dict(codex_subscription_status)
- if from_isolated_snapshot
- else CodexAuthService(_codex_binary_path()).status().to_dict()
- )
- if spec.id == "codex-subscription-realtime" and codex_subscription_ready is not None:
- codex_status["connected"] = codex_subscription_ready
- if codex_subscription_ready:
- codex_status["mode"] = "chatgpt"
- codex_status["message"] = "Connected via ChatGPT."
- else:
- codex_status["mode"] = "not_connected"
- # The isolated snapshot's message carries the precise
- # diagnosis (for example the exact required Codex version)
- # that the card's detail line renders — keep it. A status
- # read from the ORDINARY Codex profile is exactly what the
- # authoritative override corrects, so its message must not
- # survive; nor may an empty message reach the card.
- if not from_isolated_snapshot or not str(codex_status.get("message") or "").strip():
- codex_status["message"] = (
- "ChatGPT subscription voice is not ready. "
- "Reconnect with ChatGPT and review the setup status."
- )
+ codex_status = CodexAuthService(_codex_binary_path()).status().to_dict()
antigravity_status = None
if spec.id == "antigravity":
from jarvis.google_cli.auth_service import GoogleCliAuthService
@@ -624,8 +595,6 @@ def _spec_to_payload(
"configured": (
bool(antigravity_status["connected"])
if antigravity_status is not None
- else codex_subscription_ready
- if spec.id == "codex-subscription-realtime" and codex_subscription_ready is not None
else bool(codex_status["connected"] and codex_status["mode"] == "chatgpt")
if codex_status is not None and not spec.secret_keys
else _is_credential_present(
@@ -635,11 +604,8 @@ def _spec_to_payload(
),
"active": active,
"cli_installed": (
- # During a transient busy window the isolated snapshot cannot say
- # whether the CLI exists; answer from the PATH probe instead of
- # rendering a false "not installed" install prompt.
_cli_installed(spec)
- if codex_status is None or codex_status.get("reason_code") == "busy"
+ if codex_status is None
else bool(codex_status["installed"])
),
# Overlay, not a new tier (see the CU-own-provider plan): a brain
@@ -1076,10 +1042,6 @@ async def _provider_credential_present_for_binary_async(
binary_path: str | None,
) -> bool:
"""Probe sync keyrings and Codex's authoritative auth store off-loop."""
- if spec.id == "codex-subscription-realtime":
- from jarvis.codex_app_server import codex_subscription_login_ready
-
- return await codex_subscription_login_ready(binary_path)
return await asyncio.to_thread(_is_credential_present, spec, binary_path)
@@ -1154,11 +1116,6 @@ async def list_providers(request: Request) -> dict[str, Any]:
# follows is then a memo hit. See ``_warm_active_polish``.
await _warm_active_polish(request)
active_dictation = _active_polish(request)
- codex_subscription_status = await asyncio.to_thread(
- _codex_subscription_status_payload,
- _codex_binary_path(request),
- )
- codex_subscription_ready = bool(codex_subscription_status["connected"])
# When a local STT provider is ALREADY the active one, its card must report
# on the checkpoint the config names — not the catalog default. Otherwise a
# user who pinned a different Whisper size in jarvis.toml would read a
@@ -1187,8 +1144,6 @@ async def list_providers(request: Request) -> dict[str, Any]:
active_computer_use=active_computer_use,
active_dictation=active_dictation,
local_model_override=local_model_override,
- codex_subscription_ready=codex_subscription_ready,
- codex_subscription_status=codex_subscription_status,
)
for spec in PROVIDERS
# A hidden spec is withdrawn from the catalog: no card, no CLI
@@ -1243,36 +1198,6 @@ async def _run_tier_test(spec: ProviderSpec, cfg: Any, *, model: str | None = No
from jarvis.dictation.polish_probe import probe_polish_family
return await probe_polish_family(family, cfg, model=model or "")
- if spec.id == "codex-subscription-realtime":
- # This card is judged by the ISOLATED voice profile, never the
- # ordinary Codex login: the default codex_status seam would answer
- # "ok — Connected." for a user whose normal `codex login` works but
- # whose voice profile was never connected (and "not connected" for
- # the normal case of a voice-only login).
- payload = await asyncio.to_thread(
- _codex_subscription_status_payload,
- getattr(getattr(cfg, "codex", None), "binary_path", "") or None,
- )
- if payload.get("reason_code") in {"busy", "login_in_progress"}:
- # Transient — the same instant renders "checking" (or "finish the
- # login") on the card and unknown on the tab dot; a not_configured
- # verdict here would be the one dissenting surface. rate_limited
- # is the existing "transient, integration fine" status in the
- # test vocabulary, and the payload message carries the honest
- # wording for whichever transient state this is.
- return _provider_test.ProviderTestResult(
- spec.id,
- _provider_test.RATE_LIMITED,
- str(payload.get("message") or "")
- or "The ChatGPT voice status is still being checked — try again in a moment.",
- )
- isolated_status = SimpleNamespace(
- connected=bool(payload.get("connected")),
- message=str(payload.get("message") or ""),
- )
- return await _provider_test.run_provider_test(
- spec, cfg, codex_status=lambda: isolated_status, model=model
- )
return await _provider_test.run_provider_test(
spec, cfg, model=model, timeout_s=_tier_test_budget_s(spec)
)
@@ -1446,60 +1371,10 @@ async def _tier_section_health(
subject_id=spec.id,
)
try:
- if spec.id == "codex-subscription-realtime":
- # One snapshot call answers both "configured?" and "busy?" — a
- # second probe would wait out the same busy window twice.
- codex_payload = await asyncio.to_thread(_codex_subscription_status_payload, binary_path)
- if codex_payload.get("reason_code") == "busy":
- # Transiently unknown is not "needs setup": the amber dot
- # with "not connected" would contradict a card that says
- # "checking — one moment".
- return SectionHealth(
- status=_section_health.UNKNOWN,
- reason="busy",
- detail=f"{spec.label}: status check in progress",
- subject_id=spec.id,
- )
- if codex_payload.get("reason_code") == "login_in_progress":
- # The user is mid-login; an amber "not connected" dot would
- # contradict the card telling them to finish that login.
- return SectionHealth(
- status=_section_health.UNKNOWN,
- reason="login_in_progress",
- detail=f"{spec.label}: login in progress",
- subject_id=spec.id,
- )
- if codex_payload.get("reason_code") == "plan_unsupported":
- # Connected but permanently refused: "not connected or
- # configured" would name the wrong remedy in the hover text.
- return SectionHealth(
- status=_section_health.NEEDS_SETUP,
- reason="plan_unsupported",
- detail=(
- f"{spec.label}: "
- f"{codex_payload.get('message') or 'ChatGPT plan not supported'}"
- ),
- subject_id=spec.id,
- )
- if codex_payload.get("reason_code") in {
- "lifecycle_unavailable",
- "not_installed",
- }:
- # Same rule: the hover text must name the actual remedy (an
- # unsupported host, or installing the pinned release) — never
- # "not connected or configured".
- return SectionHealth(
- status=_section_health.NEEDS_SETUP,
- reason=str(codex_payload.get("reason_code")),
- detail=(f"{spec.label}: {codex_payload.get('message') or 'not available'}"),
- subject_id=spec.id,
- )
- configured = bool(codex_payload.get("connected"))
- else:
- configured = await _provider_credential_present_for_binary_async(
- spec,
- binary_path,
- )
+ configured = await _provider_credential_present_for_binary_async(
+ spec,
+ binary_path,
+ )
except Exception: # noqa: BLE001 — a probe failure is "not set up", not a crash
configured = False
if not configured:
@@ -3595,57 +3470,10 @@ async def _openai_realtime_voice_sample(
return bytes(pcm), output_rate
-async def _codex_subscription_voice_sample(
- api_key: str, *, model: str, voice: str, text: str, language: str
-) -> tuple[bytes, int]:
- """Sample the subscription voice through its ChatGPT-Live transport."""
- del api_key, model
- from jarvis.plugins.realtime.codex_subscription import ( # noqa: PLC0415
- CodexSubscriptionRealtimeProvider,
- )
- from jarvis.realtime.protocol import RealtimeSessionConfig # noqa: PLC0415
-
- provider = CodexSubscriptionRealtimeProvider(
- binary_path=_codex_binary_path(),
- # A preview sends no microphone audio and needs no input recognizer.
- input_transcriber_factory=lambda: None,
- )
- session = await provider.open_session(
- RealtimeSessionConfig(
- instructions="Speak only the trusted sample text supplied by the client.",
- language=language,
- voice=voice,
- )
- )
- pcm = bytearray()
- sample_rate = int(getattr(provider, "output_sample_rate", 24_000) or 24_000)
- try:
- await session.send_speech(text)
- async for event in session.receive():
- if event.type == "audio_delta" and event.audio is not None:
- pcm += bytes(event.audio.pcm)
- sample_rate = int(event.audio.sample_rate or sample_rate)
- elif event.type == "error":
- raise RuntimeError(str(event.error or "subscription preview failed"))
- elif event.type == "turn_complete":
- break
- finally:
- await session.close()
- return bytes(pcm), sample_rate
-
-
-# Capability metadata read by the generic route below. Subscription auth is
-# verified by the adapter itself; requiring an API key here would recreate the
-# exact billing-path parity bug this sampler closes.
-_codex_subscription_voice_sample.requires_api_key = False # type: ignore[attr-defined]
-_codex_subscription_voice_sample.timeout_s = 50.0 # type: ignore[attr-defined]
-
-
# Only providers whose preview transport can run without an interactive media
# offer appear here. A cataloged provider may intentionally omit a sampler;
# ``preview_available`` keeps the UI from rendering a button that cannot work.
_REALTIME_PREVIEW_SAMPLERS: dict[str, Any] = {
- "codex-subscription-realtime": _codex_subscription_voice_sample,
"gemini-live": _gemini_live_voice_sample,
"openai-realtime": _openai_realtime_voice_sample,
}
@@ -4535,35 +4363,6 @@ async def stt_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
}
-async def _release_codex_transports_for_voice_switch() -> None:
- """Release warm/previous Codex voice leases before changing providers."""
- from jarvis.codex_app_server import ( # noqa: PLC0415
- close_shared_codex_app_servers,
- )
-
- try:
- await asyncio.wait_for(
- asyncio.shield(close_shared_codex_app_servers()),
- timeout=15.0,
- )
- except TimeoutError as exc:
- raise HTTPException(
- status_code=409,
- detail=(
- "The previous ChatGPT subscription voice transport is still "
- "stopping. Try the provider switch again in a moment."
- ),
- ) from exc
- except Exception as exc: # noqa: BLE001 - a leaked lease must block the switch
- raise HTTPException(
- status_code=409,
- detail=(
- "The previous ChatGPT subscription voice transport could not "
- "be stopped safely. Try the provider switch again."
- ),
- ) from exc
-
-
@router.post("/realtime/switch")
async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"""Switch the active realtime provider.
@@ -4593,60 +4392,7 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"the experimental transport before activating it."
),
)
- codex_transport_released = False
- if spec.id == "codex-subscription-realtime":
- # One snapshot call answers both "configured?" and "busy?". A busy
- # window is transient — telling the user to "connect first" while the
- # card says "checking" would send them to re-do a working login.
- codex_payload = await asyncio.to_thread(
- _codex_subscription_status_payload, _codex_binary_path(request)
- )
- if codex_payload.get("reason_code") == "busy":
- # A warm transport reports the shared profile as busy. During an
- # explicit provider switch that is the resource to hand off, not
- # a reason to dead-end the button. Release it and judge the fresh
- # post-handoff status once; a real login/profile mutation remains
- # busy and still fails honestly below.
- await _release_codex_transports_for_voice_switch()
- codex_transport_released = True
- codex_payload = await asyncio.to_thread(
- _codex_subscription_status_payload,
- _codex_binary_path(request),
- )
- if codex_payload.get("reason_code") == "busy":
- raise HTTPException(
- status_code=409,
- detail=(
- "The ChatGPT subscription voice status is being checked. "
- "Try again in a moment."
- ),
- )
- if codex_payload.get("reason_code") == "login_in_progress":
- raise HTTPException(
- status_code=409,
- detail=(
- "The ChatGPT subscription login is still running. Finish "
- "it in the browser window, then activate."
- ),
- )
- if codex_payload.get("reason_code") != "plan_unsupported" and not (
- codex_payload.get("connected")
- ):
- # Answer with the payload's precise diagnosis — the generic "no
- # configured credentials" would be wrong for most codex states.
- raise HTTPException(
- status_code=409,
- detail=str(
- codex_payload.get("message")
- or "Connect the dedicated ChatGPT subscription voice login."
- ),
- )
- # plan_unsupported deliberately passes through: verify_activation
- # re-judges the LIVE account, which is the only way the sticky block
- # can clear when the plan changed back.
- credential_present = True
- else:
- credential_present = await _provider_credential_present_async(spec, request)
+ credential_present = await _provider_credential_present_async(spec, request)
if not credential_present:
raise HTTPException(
status_code=409,
@@ -4655,13 +4401,6 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"Connect or configure this provider first."
),
)
- if spec.id == "codex-subscription-realtime" and not codex_transport_released:
- # The realtime activation probe needs the same single-profile App Server
- # lease as a warm classic subscription session. Release the old owner
- # first, then let the actual realtime provider verify and keep its own
- # transport warm.
- await _release_codex_transports_for_voice_switch()
- codex_transport_released = True
try:
from jarvis.core.registry import load
from jarvis.realtime.protocol import RealtimeProvider
@@ -4685,39 +4424,14 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
detail=("The provider's activation check timed out. Try again in a moment."),
) from exc
except Exception as exc: # noqa: BLE001 - provider gate returns a safe 409
- # A refused plan already recorded its sticky diagnosis where it was
- # discovered (require_chatgpt_login) — the live call path shares it.
raise HTTPException(status_code=409, detail=str(exc)) from exc
- # The replacement provider is viable. A non-Codex replacement must release
- # any warm subscription transport before the active call is reopened. The
- # Codex branch already released the previous owner before its live probe;
- # closing again here would throw away the newly verified warm transport.
- if spec.id != "codex-subscription-realtime":
- await _release_codex_transports_for_voice_switch()
- if spec.id == "codex-subscription-realtime":
- from jarvis.codex_app_server import set_codex_subscription_activation_block
-
- # A passed activation is the proof the account works again. Off-loop:
- # the helper takes the login mutex, which worker threads may hold
- # across filesystem work.
- await asyncio.to_thread(set_codex_subscription_activation_block, None)
cfg = _resolve_cfg(request)
from jarvis.voice.subscription_profile import subscription_voice_selected
- stale_subscription_profile = bool(
- spec.id == "codex-subscription-realtime"
- and cfg is not None
- and subscription_voice_selected(cfg)
- )
- configured_mode = str(
+ effective_mode = str(
getattr(getattr(cfg, "voice", None), "mode", "pipeline") or "pipeline"
).strip().lower()
- # Releases that routed this Realtime card through the classic composition
- # persisted both the profile and Pipeline mode. That pair is repairable
- # migration damage, not a user choice: selecting the same Realtime provider
- # once restores Realtime. Ordinary provider switches preserve the mode.
- effective_mode = "realtime" if stale_subscription_profile else configured_mode
if body.persist:
try:
@@ -4727,6 +4441,8 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
)
if cfg is not None and subscription_voice_selected(cfg):
+ # Switching to a Realtime provider retires the classic
+ # subscription voice profile in the same atomic write.
set_realtime_voice_selection(
body.provider,
profile="",
@@ -4742,8 +4458,6 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
if cfg is not None and getattr(cfg, "voice", None) is not None:
try:
cfg.voice.profile = ""
- if stale_subscription_profile:
- cfg.voice.mode = "realtime"
except Exception as exc: # noqa: BLE001 - detached config is harmless
log.debug("In-memory voice.profile update skipped: %s", exc)
if cfg is not None and getattr(cfg, "brain", None) is not None:
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index 15b0c4a554..dabd22e6ca 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -751,33 +751,11 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
# ── Realtime ──────────────────────────────────────────────────────────
# Realtime voice providers share the provider-neutral RealtimeProvider
# contract. Subscription and API billing remain independently selectable.
- ProviderSpec(
- id="codex-subscription-realtime",
- label="ChatGPT subscription (Codex)",
- tier="realtime",
- auth_mode="codex",
- secret_keys=(),
- dashboard_url=None,
- login_cli=("codex", "login"),
- install_hint="npm i -g @openai/[email protected]",
- signup_url="https://chatgpt.com",
- credential_help=(
- "Beta — subscription voice through Codex is not finished yet and "
- "can break without notice. Uses the ChatGPT plan signed in through "
- "Codex. The voice itself needs no API key, and the app never switches "
- "it silently to metered API voice: if it cannot start, the call stops. "
- "Select an API Realtime provider if you want usage billing. Jarvis "
- "transcribes your side of the call with the provider selected in "
- "Speech-to-Text, so a cloud recognizer can still bill its configured "
- "key; choose an on-device one to keep input transcription local."
- ),
- experimental=True,
- # Withdrawn for v1.3.0: subscription voice over Codex's experimental
- # Realtime protocol is not reliable enough to offer. The plugin and
- # its plumbing stay shipped so an existing selection keeps resolving;
- # unhide once the transport holds a call dependably.
- hidden=True,
- ),
+ # The former "ChatGPT subscription (Codex)" realtime card was removed
+ # 2026-08-10 together with its plugin: Codex's experimental realtime
+ # surface never held a dependable call. Subscription voice continues as
+ # the stable classic-pipeline composition (voice.profile =
+ # "codex-subscription-voice") over the audited app-server text protocol.
ProviderSpec(
id="openai-realtime",
label="OpenAI Realtime",
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index c429737625..cc9900f2ed 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -287,13 +287,9 @@ async def get_voice_mode(request: Request) -> dict[str, object]:
realtime_available = prov is not None
realtime_availability_pending = False
codex_status: dict[str, object] | None = None
- if prov == "codex-subscription-realtime":
- # Runtime discovery deliberately fails open on ``busy`` because the
- # authoritative session opener can protect an in-flight/live call.
- # A STATUS surface must not convert that unknown answer into "ready":
- # the provider card says checking and mode persistence returns 409, so
- # this route reports the same pending truth while retaining the
- # resolved provider/model labels for display.
+ if profile:
+ # The classic subscription composition is judged by the ISOLATED
+ # voice-profile login, surfaced below as subscription_voice_capability.
from jarvis.ui.web.provider_routes import (
_codex_binary_path,
_codex_subscription_status_payload,
@@ -303,10 +299,6 @@ async def get_voice_mode(request: Request) -> dict[str, object]:
_codex_subscription_status_payload,
_codex_binary_path(request),
)
- reason_code = str(codex_status.get("reason_code") or "")
- if reason_code in {"busy", "login_in_progress"}:
- realtime_available = False
- realtime_availability_pending = True
requires_webrtc_offer = (
False
if profile
@@ -413,39 +405,6 @@ async def put_voice_mode(body: VoiceModeBody, request: Request) -> dict[str, obj
status_code=400,
detail="no realtime provider is configured and ready",
)
- if prov == "codex-subscription-realtime":
- # The availability bool fails OPEN on a transient busy window (by
- # design — the session opener verifies live). PERSISTING the mode
- # is a standing decision, so it gates on the actual payload: a
- # busy window answers "try again", a logged-out pinned provider
- # is refused instead of pinning a mode that cannot start.
- from jarvis.ui.web.provider_routes import (
- _codex_binary_path,
- _codex_subscription_status_payload,
- )
-
- payload = await asyncio.to_thread(
- _codex_subscription_status_payload,
- _codex_binary_path(request),
- )
- if payload.get("reason_code") in {"busy", "login_in_progress"}:
- raise HTTPException(
- status_code=409,
- detail=(
- "The ChatGPT subscription voice status is being "
- "checked. Try again in a moment."
- ),
- )
- if not payload.get("connected"):
- # The payload's precise diagnosis (plan refused, login
- # required, …) beats the generic sentence.
- raise HTTPException(
- status_code=400,
- detail=str(
- payload.get("message")
- or "no realtime provider is configured and ready"
- ),
- )
if cfg is not None and getattr(cfg, "voice", None) is not None:
try:
diff --git a/jarvis/ui/web/setup_report_routes.py b/jarvis/ui/web/setup_report_routes.py
index 73a38fc5c7..033870fa7c 100644
--- a/jarvis/ui/web/setup_report_routes.py
+++ b/jarvis/ui/web/setup_report_routes.py
@@ -120,22 +120,11 @@ def _credential_presence(request: Request) -> dict[str, bool]:
out: dict[str, bool] = {}
for spec in _providers.PROVIDERS:
try:
- if spec.id == "codex-subscription-realtime":
- # This card is judged by the ISOLATED voice profile; the
- # generic probe would read the ORDINARY Codex login and make
- # the device-parity report lie in both directions. A busy
- # snapshot reads as absent (fail-closed) — the report is a
- # point-in-time diagnostic, not a gate.
- payload = _providers._codex_subscription_status_payload(
- binary_path
- )
- present = bool(payload.get("connected"))
- else:
- present = bool(
- _providers._is_credential_present(
- spec, binary_path if spec.id == "codex" else None
- )
+ present = bool(
+ _providers._is_credential_present(
+ spec, binary_path if spec.id == "codex" else None
)
+ )
except Exception as exc: # noqa: BLE001 — an unreadable slot reads as absent
log.debug("setup-report: credential probe for %s failed: %s", spec.id, exc)
present = False
diff --git a/pyproject.toml b/pyproject.toml
index bfbb6e9511..e1c1a58b7a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -567,7 +567,11 @@ discord = "jarvis.channels.discord:DiscordChannel"
[project.entry-points."jarvis.realtime"]
# Provider-neutral speech-to-speech plugins. Every adapter loads lazily; the
# orchestrator chooses a credential-ready family and crosses families on failure.
-codex-subscription-realtime = "jarvis.plugins.realtime.codex_subscription:CodexSubscriptionRealtimeProvider"
+# The former codex-subscription-realtime adapter was removed 2026-08-10: the
+# Codex app-server realtime surface is experimental, has no turn-boundary or
+# tool events, and never held a dependable call. The ChatGPT plan keeps voice
+# through the stable classic-pipeline composition (voice.profile =
+# "codex-subscription-voice"), which uses the audited app-server TEXT protocol.
openai-realtime = "jarvis.plugins.realtime.openai_realtime:OpenAIRealtimeProvider"
gemini-live = "jarvis.plugins.realtime.gemini_live:GeminiLiveProvider"
# Self-hosted endpoint speaking the same realtime protocol — the local option
diff --git a/scripts/codex_live_probe.py b/scripts/codex_live_probe.py
deleted file mode 100644
index d1c00525dc..0000000000
--- a/scripts/codex_live_probe.py
+++ /dev/null
@@ -1,160 +0,0 @@
-"""Drive real headless ChatGPT-Live calls against the codex-subscription path.
-
-The reproduction tool this provider never had: every earlier fix round was
-verified by reading ``data/jarvis_desktop.log`` after a live call died. This
-CLI runs scripted calls (committed speech fixtures, real adapter, real
-app-server, real WebRTC) and prints a PASS/WARN/FAIL verdict per scenario.
-
-Every call consumes the ChatGPT subscription's realtime usage - the run is
-capped (``--max-calls``, default 5; more needs ``--yes-really``). The desktop
-app must be STOPPED first: the fail-closed voice-profile lock otherwise
-refuses the probe (exit 3).
-
-Usage::
-
- python scripts/codex_live_probe.py --dump # contract discovery
- python scripts/codex_live_probe.py --scenario three_turns_de
- python scripts/codex_live_probe.py --scenario three_turns_de \
- --scenario barge_in_followup --scenario silence_no_selftalk
- python scripts/diag_voice_sessions.py --harness <out>/round.jsonl
-
-Exit codes: 0 pass · 1 assert failed · 2 environment missing · 3 the app
-holds the profile lock.
-"""
-from __future__ import annotations
-
-import argparse
-import asyncio
-import json
-import sys
-import time
-from pathlib import Path
-
-if hasattr(sys.stdout, "reconfigure"):
- sys.stdout.reconfigure(encoding="utf-8") # type: ignore[union-attr]
-
-# The worktree the script lives in is the code that runs, regardless of where
-# the editable install points (BUG-006 class) - same pattern as
-# scripts/diag_voice_sessions.py.
-REPO_ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(REPO_ROOT))
-
-from jarvis.diagnostics.realtime_probe import ( # noqa: E402
- ProbeEnvironmentError,
- load_scenario,
- run_dump,
- run_scenario,
-)
-
-DEFAULT_MAX_CALLS = 5
-
-
-def _print_summary(summary: dict) -> None:
- verdict = "PASS" if summary.get("passed") else "FAIL"
- print(f"\nscenario {summary.get('scenario')}: {verdict}")
- for name, entry in (summary.get("asserts") or {}).items():
- print(f" [{entry['status']:4}] {name}: {entry['detail']}")
- postmortem = summary.get("postmortem") or {}
- if postmortem:
- print(
- f" postmortem: turns={postmortem.get('turns_completed', 0)} "
- f"ready={postmortem.get('ready_ms', 0)}ms "
- f"first_audio={postmortem.get('first_audio_ms', 0)}ms "
- f"rebuilds={postmortem.get('rebuilds', 0)}"
- )
-
-
-async def _run(args: argparse.Namespace) -> int:
- calls_planned = (1 if args.dump else 0) + len(args.scenario)
- if calls_planned == 0:
- print("nothing to do: pass --dump and/or --scenario <name>")
- return 2
- if calls_planned > args.max_calls and not args.yes_really:
- print(
- f"{calls_planned} live calls exceed the cap of {args.max_calls}; "
- "re-run with --yes-really if you mean it"
- )
- return 2
- print(
- f"NOTE: {calls_planned} live call(s) will bill the ChatGPT "
- "subscription's realtime usage."
- )
-
- stamp = time.strftime("%Y%m%d-%H%M%S")
- base = args.out or (REPO_ROOT / "data" / "diagnostics" / "codex_live" / stamp)
- base = Path(base)
- exit_code = 0
-
- if args.dump:
- print("\n-- dump round (contract discovery) --")
- summary = await run_dump(out_dir=base / "dump")
- print(json.dumps(summary, indent=2, ensure_ascii=False, default=str))
- terminal = summary.get("terminal_in_frozenset") or []
- candidates = summary.get("terminal_candidates") or []
- if terminal:
- print(f"terminal response item observed: {terminal} - IN _TERMINAL_RESPONSE_ITEMS")
- elif candidates:
- print(
- f"terminal response item observed: {candidates} - "
- "NOT IN _TERMINAL_RESPONSE_ITEMS (update the frozenset)"
- )
- else:
- print(
- "no terminal-shaped item observed - the quiescence backstop "
- "remains the only boundary"
- )
-
- budgets = {
- "ready_s": args.budget_ready_s,
- "first_audio_s": args.budget_first_audio_s,
- "enforce": args.enforce_budgets,
- }
- for name in args.scenario:
- print(f"\n-- scenario {name} --")
- scenario = load_scenario(name)
- summary = await run_scenario(
- scenario,
- out_dir=base / name,
- budgets=budgets,
- with_delegate=args.with_delegate,
- )
- _print_summary(summary)
- if not summary.get("passed"):
- exit_code = 1
-
- print(f"\ncaptures under {base}")
- return exit_code
-
-
-def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
- parser.add_argument("--scenario", action="append", default=[])
- parser.add_argument("--dump", action="store_true")
- parser.add_argument("--out", type=Path, default=None)
- parser.add_argument("--max-calls", type=int, default=DEFAULT_MAX_CALLS)
- parser.add_argument("--yes-really", action="store_true")
- parser.add_argument("--budget-ready-s", type=float, default=4.0)
- parser.add_argument("--budget-first-audio-s", type=float, default=6.0)
- parser.add_argument(
- "--enforce-budgets",
- action="store_true",
- help="spawn budget overruns FAIL instead of WARN (the B6 flip)",
- )
- parser.add_argument(
- "--with-delegate",
- action="store_true",
- help="wire the configured brain so the delegation scenario can run",
- )
- args = parser.parse_args()
- try:
- return asyncio.run(_run(args))
- except ProbeEnvironmentError as exc:
- print(f"probe environment: {exc}")
- return exc.exit_code
- except KeyboardInterrupt:
- print("interrupted")
- return 130
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/scripts/config-soll.json b/scripts/config-soll.json
index a9673b266c..05e0ae936f 100644
--- a/scripts/config-soll.json
+++ b/scripts/config-soll.json
@@ -123,9 +123,6 @@
"cu_model": "qwen3.5:4b",
"model": "qwen3.5:4b"
},
- "brain.providers.codex-subscription-realtime": {
- "voice": "cove"
- },
"brain.providers.grok": {
"tool_model": "grok-4.5",
"cu_model": "grok-4.5"
diff --git a/tests/contract/test_realtime_provider_contract.py b/tests/contract/test_realtime_provider_contract.py
index c0c0757c2a..9c43809dd0 100644
--- a/tests/contract/test_realtime_provider_contract.py
+++ b/tests/contract/test_realtime_provider_contract.py
@@ -10,9 +10,6 @@ from typing import Any
import pytest
-from jarvis.plugins.realtime.codex_subscription import (
- CodexSubscriptionRealtimeProvider,
-)
from jarvis.plugins.realtime.gemini_live import GeminiLiveProvider
from jarvis.plugins.realtime.openai_realtime import (
LocalRealtimeProvider,
@@ -21,11 +18,11 @@ from jarvis.plugins.realtime.openai_realtime import (
from jarvis.realtime.protocol import RealtimeEvent, RealtimeProvider
from jarvis.realtime.session import RealtimeVoiceSession
-_CAPABILITY_LIMITED_PROVIDER_CLASSES = tuple(
- provider_cls
- for provider_cls in (CodexSubscriptionRealtimeProvider,)
- if not bool(getattr(provider_cls, "supports_direct_tools", True))
-)
+# Every installed provider that declares supports_direct_tools=False must pass
+# the delegate/decline contracts below. Empty today (the capability-limited
+# codex-subscription-realtime adapter was removed 2026-08-10); the harness
+# stays so a future external-login provider is pinned automatically.
+_CAPABILITY_LIMITED_PROVIDER_CLASSES: tuple[type[Any], ...] = ()
def _session_config(tool_mode: str) -> SimpleNamespace:
@@ -112,20 +109,6 @@ def test_provider_is_structurally_conformant(provider_cls, provider_id, input_ra
assert provider.credential_candidates
-def test_subscription_provider_is_structurally_conformant_without_api_key() -> None:
- provider = CodexSubscriptionRealtimeProvider()
-
- assert isinstance(provider, RealtimeProvider)
- assert provider.supports_realtime is True
- assert provider.name == "codex-subscription-realtime"
- assert provider.input_sample_rate == 24_000
- assert provider.output_sample_rate == 24_000
- assert provider.credential_candidates == ()
- # Jarvis owns the WebRTC peer in-process (ChatGPT-Live carries audio on
- # the media track), so no UI has to broker a signalling offer any more.
- assert provider.requires_webrtc_offer is False
-
-
@pytest.mark.parametrize("provider_cls", _CAPABILITY_LIMITED_PROVIDER_CLASSES)
def test_capability_limited_provider_resolves_callable_brain_to_delegate(
provider_cls: type[Any],
@@ -228,7 +211,6 @@ async def test_unconfigured_local_provider_probe_is_false() -> None:
[
Path("jarvis/plugins/realtime/openai_realtime.py"),
Path("jarvis/plugins/realtime/gemini_live.py"),
- Path("jarvis/plugins/realtime/codex_subscription.py"),
],
)
def test_plugin_module_imports_no_jarvis_modules(path: Path):
diff --git a/tests/fixtures/audio/realtime/de_fahrrad.wav b/tests/fixtures/audio/realtime/de_fahrrad.wav
deleted file mode 100644
index d0006f10ba..0000000000
Binary files a/tests/fixtures/audio/realtime/de_fahrrad.wav and /dev/null differ
diff --git a/tests/fixtures/audio/realtime/de_giraffe.wav b/tests/fixtures/audio/realtime/de_giraffe.wav
deleted file mode 100644
index d82dba1f8e..0000000000
Binary files a/tests/fixtures/audio/realtime/de_giraffe.wav and /dev/null differ
diff --git a/tests/fixtures/audio/realtime/de_tandelbrook.wav b/tests/fixtures/audio/realtime/de_tandelbrook.wav
deleted file mode 100644
index 2087e61cb6..0000000000
Binary files a/tests/fixtures/audio/realtime/de_tandelbrook.wav and /dev/null differ
diff --git a/tests/fixtures/audio/realtime/en_bicycle.wav b/tests/fixtures/audio/realtime/en_bicycle.wav
deleted file mode 100644
index df9abc043a..0000000000
Binary files a/tests/fixtures/audio/realtime/en_bicycle.wav and /dev/null differ
diff --git a/tests/fixtures/audio/realtime/en_giraffe.wav b/tests/fixtures/audio/realtime/en_giraffe.wav
deleted file mode 100644
index 437482356c..0000000000
Binary files a/tests/fixtures/audio/realtime/en_giraffe.wav and /dev/null differ
diff --git a/tests/fixtures/audio/realtime/en_glimmerpond.wav b/tests/fixtures/audio/realtime/en_glimmerpond.wav
deleted file mode 100644
index 9d53de79bd..0000000000
Binary files a/tests/fixtures/audio/realtime/en_glimmerpond.wav and /dev/null differ
diff --git a/tests/fixtures/audio/realtime/en_tandelbrook.wav b/tests/fixtures/audio/realtime/en_tandelbrook.wav
deleted file mode 100644
index 2b0f634a37..0000000000
Binary files a/tests/fixtures/audio/realtime/en_tandelbrook.wav and /dev/null differ
diff --git a/tests/fixtures/audio/realtime/en_zebrastorm.wav b/tests/fixtures/audio/realtime/en_zebrastorm.wav
deleted file mode 100644
index b518d5abb5..0000000000
Binary files a/tests/fixtures/audio/realtime/en_zebrastorm.wav and /dev/null differ
diff --git a/tests/fixtures/audio/realtime/manifest.json b/tests/fixtures/audio/realtime/manifest.json
deleted file mode 100644
index 16e0c04493..0000000000
--- a/tests/fixtures/audio/realtime/manifest.json
+++ /dev/null
@@ -1,83 +0,0 @@
-[
- {
- "id": "en_giraffe",
- "path": "en_giraffe.wav",
- "language": "en",
- "text": "What color is the violet giraffe from my example? Answer in one short sentence.",
- "nonce": "violet giraffe",
- "duration_ms": 5534,
- "sample_rate": 24000
- },
- {
- "id": "en_tandelbrook",
- "path": "en_tandelbrook.wav",
- "language": "en",
- "text": "Please repeat my invented word tandelbrook exactly once.",
- "nonce": "tandelbrook",
- "duration_ms": 4172,
- "sample_rate": 24000
- },
- {
- "id": "en_bicycle",
- "path": "en_bicycle.wav",
- "language": "en",
- "text": "How many wheels does my imaginary quintuple bicycle have?",
- "nonce": "quintuple bicycle",
- "duration_ms": 3924,
- "sample_rate": 24000
- },
- {
- "id": "en_glimmerpond",
- "path": "en_glimmerpond.wav",
- "language": "en",
- "text": "Name one word that rhymes with my invented word glimmerpond.",
- "nonce": "glimmerpond",
- "duration_ms": 4140,
- "sample_rate": 24000
- },
- {
- "id": "en_zebrastorm",
- "path": "en_zebrastorm.wav",
- "language": "en",
- "text": "In one sentence, what would a zebrastorm picnic be?",
- "nonce": "zebrastorm",
- "duration_ms": 3848,
- "sample_rate": 24000
- },
- {
- "id": "de_giraffe",
- "path": "de_giraffe.wav",
- "language": "de",
- "text": "Welche Farbe hat die violette Giraffe aus meinem Beispiel? Antworte in einem kurzen Satz.",
- "nonce": "violette Giraffe",
- "duration_ms": 5260,
- "sample_rate": 24000
- },
- {
- "id": "de_tandelbrook",
- "path": "de_tandelbrook.wav",
- "language": "de",
- "text": "Bitte wiederhole mein erfundenes Wort Tandelbrook genau einmal.",
- "nonce": "Tandelbrook",
- "duration_ms": 4170,
- "sample_rate": 24000
- },
- {
- "id": "de_fahrrad",
- "path": "de_fahrrad.wav",
- "language": "de",
- "text": "Wie viele Räder hat mein erfundenes Fünffach-Fahrrad?",
- "nonce": "Fünffach-Fahrrad",
- "duration_ms": 3225,
- "sample_rate": 24000
- },
- {
- "id": "room_noise",
- "path": "room_noise.wav",
- "language": "",
- "text": "",
- "nonce": "",
- "duration_ms": 8000,
- "sample_rate": 24000
- }
-]
diff --git a/tests/fixtures/audio/realtime/room_noise.wav b/tests/fixtures/audio/realtime/room_noise.wav
deleted file mode 100644
index 38cd72dcf5..0000000000
Binary files a/tests/fixtures/audio/realtime/room_noise.wav and /dev/null differ
diff --git a/tests/integration/realtime/scenarios/barge_in_followup.json b/tests/integration/realtime/scenarios/barge_in_followup.json
deleted file mode 100644
index 40389e55d7..0000000000
--- a/tests/integration/realtime/scenarios/barge_in_followup.json
+++ /dev/null
@@ -1,45 +0,0 @@
-{
- "name": "barge_in_followup",
- "description": "Reviewer checklist item 1: interrupt a running answer, ask a follow-up, and the follow-up must be answered (the speech-edge/entitlement regression class).",
- "steps": [
- {
- "silence_s": 1.0
- },
- {
- "speak": "en_zebrastorm"
- },
- {
- "barge_in": {
- "after_reply_ms": 700,
- "then_speak": "en_giraffe"
- }
- },
- {
- "wait_reply": {
- "timeout_s": 20
- }
- },
- {
- "silence_s": 0.75
- },
- {
- "speak": "en_glimmerpond"
- },
- {
- "wait_reply": {
- "timeout_s": 20
- }
- },
- {
- "end": {}
- }
- ],
- "asserts": [
- "turns>=2",
- "no_ungrounded",
- "no_roleplay",
- "no_rebuilds",
- "mic_wall_clock",
- "clean_close"
- ]
-}
diff --git a/tests/integration/realtime/scenarios/delegation.json b/tests/integration/realtime/scenarios/delegation.json
deleted file mode 100644
index 680b47d594..0000000000
--- a/tests/integration/realtime/scenarios/delegation.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "name": "delegation",
- "description": "Opt-in (needs --with-delegate): one action-shaped request must dispatch a delegation and speak its result without killing the call. Reviewer checklist item 2.",
- "steps": [
- {
- "silence_s": 1.0
- },
- {
- "speak": "en_giraffe"
- },
- {
- "wait_reply": {
- "timeout_s": 20
- }
- },
- {
- "silence_s": 0.75
- },
- {
- "speak": "en_tandelbrook"
- },
- {
- "wait_reply": {
- "timeout_s": 30
- }
- },
- {
- "end": {}
- }
- ],
- "asserts": [
- "turns>=2",
- "no_ungrounded",
- "no_roleplay",
- "no_rebuilds",
- "clean_close"
- ]
-}
diff --git a/tests/integration/realtime/scenarios/silence_no_selftalk.json b/tests/integration/realtime/scenarios/silence_no_selftalk.json
deleted file mode 100644
index 63256c7c88..0000000000
--- a/tests/integration/realtime/scenarios/silence_no_selftalk.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "name": "silence_no_selftalk",
- "description": "Ten seconds of room tone and nothing else: beyond at most one bounded greeting, the assistant must stay silent (the 17:03 two-person demo dialogue class).",
- "steps": [
- {"silence_s": 10},
- {"end": {}}
- ],
- "asserts": [
- "no_selftalk",
- "no_rebuilds",
- "mic_wall_clock",
- "clean_close"
- ]
-}
diff --git a/tests/integration/realtime/scenarios/split_reply_pause.json b/tests/integration/realtime/scenarios/split_reply_pause.json
deleted file mode 100644
index c34a72dff9..0000000000
--- a/tests/integration/realtime/scenarios/split_reply_pause.json
+++ /dev/null
@@ -1,39 +0,0 @@
-{
- "name": "split_reply_pause",
- "description": "A prompt that invites a longer, pause-bearing answer: generation pauses beyond the 1.2s backstop must not produce audible seams or splices (Fix E's live guard).",
- "steps": [
- {
- "silence_s": 1.0
- },
- {
- "speak": "en_zebrastorm"
- },
- {
- "wait_reply": {
- "timeout_s": 25
- }
- },
- {
- "silence_s": 0.75
- },
- {
- "speak": "de_fahrrad"
- },
- {
- "wait_reply": {
- "timeout_s": 25
- }
- },
- {
- "end": {}
- }
- ],
- "asserts": [
- "turns>=2",
- "no_ungrounded",
- "no_roleplay",
- "audio_continuity",
- "no_rebuilds",
- "clean_close"
- ]
-}
diff --git a/tests/integration/realtime/scenarios/three_turns_de.json b/tests/integration/realtime/scenarios/three_turns_de.json
deleted file mode 100644
index dd24ce6b51..0000000000
--- a/tests/integration/realtime/scenarios/three_turns_de.json
+++ /dev/null
@@ -1,52 +0,0 @@
-{
- "name": "three_turns_de",
- "description": "The headline multi-turn guard: two German turns, then one English turn, each answered. Pins the 50% one-turn death rate at zero.",
- "steps": [
- {
- "silence_s": 1.0
- },
- {
- "speak": "de_giraffe"
- },
- {
- "wait_reply": {
- "timeout_s": 20
- }
- },
- {
- "silence_s": 0.75
- },
- {
- "speak": "de_tandelbrook"
- },
- {
- "wait_reply": {
- "timeout_s": 20
- }
- },
- {
- "silence_s": 0.75
- },
- {
- "speak": "en_bicycle"
- },
- {
- "wait_reply": {
- "timeout_s": 20
- }
- },
- {
- "end": {}
- }
- ],
- "asserts": [
- "turns>=3",
- "no_ungrounded",
- "no_roleplay",
- "audio_continuity",
- "no_rebuilds",
- "mic_wall_clock",
- "spawn_budget",
- "clean_close"
- ]
-}
diff --git a/tests/integration/realtime/test_codex_live_call.py b/tests/integration/realtime/test_codex_live_call.py
deleted file mode 100644
index 4ec65f2540..0000000000
--- a/tests/integration/realtime/test_codex_live_call.py
+++ /dev/null
@@ -1,46 +0,0 @@
-"""Env-gated REAL ChatGPT-Live call through the production codex path.
-
-Never runs in CI and never by accident: it needs the explicit
-``JARVIS_CODEX_LIVE=1`` opt-in (each run bills the maintainer's ChatGPT
-subscription realtime usage), a logged-in Codex voice profile, aiortc, and
-the desktop app STOPPED (the profile lock refuses the probe otherwise —
-that refusal is itself fail-closed behavior, reported as a skip here).
-"""
-
-from __future__ import annotations
-
-import os
-from pathlib import Path
-
-import pytest
-
-pytestmark = [pytest.mark.integration, pytest.mark.slow, pytest.mark.e2e]
-
-if os.environ.get("JARVIS_CODEX_LIVE") != "1": # noqa: SIM108 - collection-time gate
- pytest.skip(
- "live codex probe needs the explicit JARVIS_CODEX_LIVE=1 opt-in "
- "(it bills the ChatGPT subscription)",
- allow_module_level=True,
- )
-
-from jarvis.diagnostics.realtime_probe import ( # noqa: E402
- ProbeEnvironmentError,
- load_scenario,
- run_scenario,
-)
-
-
-async def test_three_turns_de_live(tmp_path: Path) -> None:
- try:
- summary = await run_scenario(
- load_scenario("three_turns_de"),
- out_dir=tmp_path / "three_turns_de",
- )
- except ProbeEnvironmentError as exc:
- pytest.skip(str(exc))
- failed = {
- name: entry
- for name, entry in summary["asserts"].items()
- if entry["status"] == "fail"
- }
- assert not failed, f"live scenario failed: {failed}"
diff --git a/tests/integration/realtime/test_codex_multi_turn.py b/tests/integration/realtime/test_codex_multi_turn.py
deleted file mode 100644
index dfcbd0e900..0000000000
--- a/tests/integration/realtime/test_codex_multi_turn.py
+++ /dev/null
@@ -1,1046 +0,0 @@
-"""Multi-turn end-to-end guards for a codex-shaped realtime transport.
-
-The gap these close: ``tests/unit/realtime/test_codex_subscription.py`` drives
-the adapter's ``receive()`` in isolation, and ``test_session.py`` drives a fake
-whose capability tuple is not the codex one — so NO test anywhere ran a
-codex-shaped provider through ``RealtimeVoiceSession`` for more than one turn.
-"Works once, then only listens" is by definition a turn-2 failure, so it could
-reach the maintainer with a green suite.
-
-Everything here is hermetic and deterministic: no network, no aiortc, no
-app-server, no real clock. Provider events are pushed through an in-memory
-queue and every wait is bounded, so a wedge fails the test instead of hanging
-the run.
-
-Scope boundary, stated honestly: this drives the transport contract at the
-SESSION level. The adapter's own grounding gate (``_begin_response``) and its
-quiescence backstop live below the events pushed here; the fake emits the
-normalized stream that gate produces, so what these tests pin is the session
-half — that a codex-shaped stream keeps the call answering, turn after turn.
-"""
-
-from __future__ import annotations
-
-import asyncio
-from types import SimpleNamespace
-from typing import Any
-
-import pytest
-
-from jarvis.core.bus import EventBus
-from jarvis.core.protocols import AudioChunk
-from jarvis.realtime import session as session_mod
-from jarvis.realtime.protocol import RealtimeEvent
-from jarvis.realtime.session import RealtimeVoiceSession
-
-# Every await in this module is bounded by this. A regression must report as a
-# failure, never as a stalled CI job.
-TIMEOUT_S = 5.0
-
-PROVIDER_NAME = "codex-subscription"
-INPUT_RATE = 24_000
-OUTPUT_RATE = 24_000
-
-#: The real adapter's capability tuple. Pinned against the production class by
-#: ``test_the_fake_mirrors_the_real_codex_capability_tuple`` so this harness
-#: cannot quietly drift into testing a provider that does not exist.
-CODEX_CAPABILITIES: dict[str, bool] = {
- "creates_responses_automatically": True,
- "supports_prompted_response_retry": True,
- "isolates_response_generations": True,
- "supports_direct_tools": False,
- "supports_tool_updates": False,
- "direct_speech_is_authoritative": True,
- "rebuild_on_transport_death": True,
-}
-
-
-def _pcm(sample_count: int = 240, value: int = 1200) -> bytes:
- return value.to_bytes(2, "little", signed=True) * sample_count
-
-
-def _audio(sample_count: int = 240) -> AudioChunk:
- return AudioChunk(
- pcm=_pcm(sample_count),
- sample_rate=OUTPUT_RATE,
- timestamp_ns=0,
- )
-
-
-class _CodexShapedWire:
- """A provider session with the codex capability tuple and a pushable stream.
-
- ChatGPT-Live carries audio on a WebRTC media track and supplies no
- server-side user transcription, so the user transcripts below stand for the
- adapter's LOCAL recognizer — which is the only source of them on that
- transport, and therefore the only thing that can open a turn.
- """
-
- session_id = "codex-shaped-wire"
- creates_responses_automatically = CODEX_CAPABILITIES[
- "creates_responses_automatically"
- ]
- supports_prompted_response_retry = CODEX_CAPABILITIES[
- "supports_prompted_response_retry"
- ]
- isolates_response_generations = CODEX_CAPABILITIES[
- "isolates_response_generations"
- ]
- supports_direct_tools = CODEX_CAPABILITIES["supports_direct_tools"]
- supports_tool_updates = CODEX_CAPABILITIES["supports_tool_updates"]
- direct_speech_is_authoritative = CODEX_CAPABILITIES[
- "direct_speech_is_authoritative"
- ]
- rebuild_on_transport_death = CODEX_CAPABILITIES["rebuild_on_transport_death"]
-
- def __init__(self) -> None:
- self._events: asyncio.Queue[Any] = asyncio.Queue()
- self.sent_audio: list[AudioChunk] = []
- self.spoken: list[str] = []
- self.texts: list[str] = []
- self.text_appended = asyncio.Event()
- self.session_updates: list[dict[str, Any]] = []
- self.response_requests = 0
- self.interrupts = 0
- self.closed = False
-
- # -- test-side driving ------------------------------------------------
- def push(self, *events: RealtimeEvent) -> None:
- for event in events:
- self._events.put_nowait(event)
-
- # -- provider contract ------------------------------------------------
- async def send_audio(self, chunk: AudioChunk) -> None:
- self.sent_audio.append(chunk)
-
- async def receive(self): # noqa: ANN201 - async generator, protocol shape
- while True:
- event = await self._events.get()
- if event is None:
- return
- yield event
-
- async def update_session(
- self,
- *,
- instructions: str | None = None,
- language: str | None = None,
- tools: tuple[dict[str, Any], ...] | None = None,
- ) -> None:
- self.session_updates.append(
- {"instructions": instructions, "language": language, "tools": tools}
- )
-
- async def request_response(self, *, required_tool: str | None = None) -> None:
- # ChatGPT-Live's server VAD creates responses on its own; the real
- # adapter's request_response is a no-op for exactly this reason.
- del required_tool
- self.response_requests += 1
-
- async def send_text(self, text: str) -> None:
- self.texts.append(text)
- self.text_appended.set()
-
- async def send_speech(self, text: str) -> None:
- self.spoken.append(text)
-
- async def truncate(self, audio_end_ms: int) -> None:
- del audio_end_ms
-
- async def interrupt(self) -> None:
- self.interrupts += 1
-
- async def send_tool_result(
- self, call_id: str, name: str, result: dict[str, Any]
- ) -> None:
- del call_id, name, result
- raise RuntimeError("codex subscription realtime does not execute tools")
-
- async def close(self) -> None:
- self.closed = True
- self._events.put_nowait(None)
-
-
-class _CodexShapedProvider:
- name = PROVIDER_NAME
- supports_realtime = True
- input_sample_rate = INPUT_RATE
- output_sample_rate = OUTPUT_RATE
-
- def __init__(self) -> None:
- self.sessions: list[_CodexShapedWire] = []
- self.opened_with: Any = None
-
- async def can_open_duplex_session(self) -> bool:
- return True
-
- async def open_session(self, config: Any) -> _CodexShapedWire:
- self.opened_with = config
- wire = _CodexShapedWire()
- self.sessions.append(wire)
- return wire
-
-
-class _Surface:
- """Records what the desktop surface would render, with bounded waiting."""
-
- def __init__(self) -> None:
- self.json: list[dict[str, Any]] = []
- self.binary: list[bytes] = []
- self._tick = asyncio.Event()
-
- async def send_json(self, message: dict[str, Any]) -> None:
- self.json.append(dict(message))
- self._tick.set()
-
- async def send_binary(self, data: bytes) -> None:
- self.binary.append(bytes(data))
- self._tick.set()
-
- def mark(self) -> int:
- return len(self.json)
-
- async def wait_json(
- self, predicate, *, since: int = 0, timeout_s: float = TIMEOUT_S
- ) -> dict[str, Any]:
- async def _loop() -> dict[str, Any]:
- while True:
- # Clear BEFORE scanning, so a message that arrives during the
- # scan still wakes the next iteration.
- self._tick.clear()
- for message in self.json[since:]:
- if predicate(message):
- return message
- await self._tick.wait()
-
- try:
- return await asyncio.wait_for(_loop(), timeout_s)
- except TimeoutError: # pragma: no cover - only on a real regression
- raise AssertionError(
- f"no matching surface message within {timeout_s:.1f}s; "
- f"saw {[m.get('type') for m in self.json[since:]]}"
- ) from None
-
- async def wait_binary(
- self, *, at_least: int, timeout_s: float = TIMEOUT_S
- ) -> None:
- async def _loop() -> None:
- while len(self.binary) < at_least:
- self._tick.clear()
- if len(self.binary) >= at_least:
- return
- await self._tick.wait()
-
- try:
- await asyncio.wait_for(_loop(), timeout_s)
- except TimeoutError: # pragma: no cover - only on a real regression
- raise AssertionError(
- f"expected at least {at_least} audio frames within "
- f"{timeout_s:.1f}s; got {len(self.binary)}"
- ) from None
-
-
-def _config() -> SimpleNamespace:
- return SimpleNamespace(
- brain=SimpleNamespace(
- reply_language="en",
- providers={PROVIDER_NAME: SimpleNamespace(model="", voice="cove")},
- ),
- stt=SimpleNamespace(language="auto"),
- voice=SimpleNamespace(mode="realtime", realtime_tool_mode="delegate"),
- )
-
-
-async def _open_call() -> tuple[
- RealtimeVoiceSession, _CodexShapedProvider, _CodexShapedWire, _Surface
-]:
- """Open one desktop-shaped half-duplex call and return its parts."""
- surface = _Surface()
- provider = _CodexShapedProvider()
- session = RealtimeVoiceSession(
- session_id="codex-multi-turn",
- send_binary=surface.send_binary,
- send_json=surface.send_json,
- providers=[provider],
- config=_config(),
- bus=EventBus(),
- surface="desktop",
- # The desktop configuration: the microphone is muted while the
- # assistant speaks, which is exactly what turns a stuck output state
- # into "it stopped listening".
- half_duplex=True,
- browser_sample_rate=INPUT_RATE,
- )
- await asyncio.wait_for(
- session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),
- TIMEOUT_S,
- )
- # The real desktop surface supplies this probe. This in-memory surface has
- # no device queue, so every forwarded frame is drained immediately.
- session.set_playback_probe(lambda: False)
- assert provider.sessions, "the provider was never opened"
- return session, provider, provider.sessions[0], surface
-
-
-async def _assert_at_rest(
- session: RealtimeVoiceSession, wire: _CodexShapedWire, *, note: str
-) -> None:
- """The call must be genuinely idle AND still listening.
-
- "Still listening" is the load-bearing half: under half duplex a stuck
- output state silently swallows every microphone frame, so the call looks
- alive while nothing the user says can reach the provider again.
- """
- assert session._output_active is False, f"{note}: output still active" # noqa: SLF001
- assert session._response_requested_for_turn is False, ( # noqa: SLF001
- f"{note}: a response is still marked as requested"
- )
- assert session._transport_rebuild_pending is None, ( # noqa: SLF001
- f"{note}: a transport rebuild is still pending"
- )
- assert session._advised_reconnect_detail is None, ( # noqa: SLF001
- f"{note}: a reconnect is still advised"
- )
- assert session._external_update is None, ( # noqa: SLF001
- f"{note}: an external update is still owned by the turn"
- )
-
- before = len(wire.sent_audio)
- await asyncio.wait_for(session.handle_audio_frame(_pcm()), TIMEOUT_S)
- assert len(wire.sent_audio) == before + 1, (
- f"{note}: the microphone no longer reaches the provider — the call is "
- "wedged even though it looks alive"
- )
-
-
-#: Ordinal words, not digits: the voice scrubber spells numbers out for TTS
-#: ("answer 1." -> "answer one."), so a digit in fixture text would assert
-#: against the scrubber rather than against the turn machinery.
-_ORDINALS = {1: "first", 2: "second", 3: "third"}
-
-
-def _question(index: int) -> str:
- return f"the {_ORDINALS[index]} question"
-
-
-def _answer(index: int) -> str:
- return f"The {_ORDINALS[index]} reply."
-
-
-def _turn_events(index: int, *, audio_frames: int = 2) -> list[RealtimeEvent]:
- """One ordinary turn as the codex adapter normalizes it."""
- events = [
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(
- type="input_transcript", text=_question(index), is_final=True
- ),
- RealtimeEvent(type="output_transcript_delta", text=_answer(index)),
- ]
- events.extend(RealtimeEvent(type="audio_delta", audio=_audio()) for _ in range(audio_frames))
- events.append(RealtimeEvent(type="turn_complete"))
- return events
-
-
-async def _run_turn(
- session: RealtimeVoiceSession,
- wire: _CodexShapedWire,
- surface: _Surface,
- index: int,
-) -> None:
- since = surface.mark()
- wire.push(*_turn_events(index))
- await surface.wait_json(lambda m: m.get("type") == "turn_complete", since=since)
-
-
-async def _end(session: RealtimeVoiceSession) -> None:
- await asyncio.wait_for(session.end(reason="test"), TIMEOUT_S)
-
-
-# -- the fake must not drift from the adapter it stands in for --------------
-
-
-def test_the_fake_mirrors_the_real_codex_capability_tuple() -> None:
- """A harness that tests a provider shape nobody ships proves nothing."""
- from jarvis.plugins.realtime.codex_subscription import (
- _CodexSubscriptionRealtimeSession,
- )
-
- for attribute, expected in CODEX_CAPABILITIES.items():
- assert getattr(_CodexSubscriptionRealtimeSession, attribute) == expected, (
- f"the real adapter changed {attribute}; this harness is now testing "
- "a provider shape that does not exist"
- )
- assert getattr(_CodexShapedWire, attribute) == expected
-
- # Trusted verbatim speech is the channel delegate readbacks ride on; a fake
- # without it cannot reproduce the turn shapes below.
- assert callable(getattr(_CodexSubscriptionRealtimeSession, "send_speech", None))
- assert callable(getattr(_CodexShapedWire, "send_speech", None))
-
-
-async def test_wrong_language_uses_prompted_subscription_retry() -> None:
- """The subscription's ordinary response request is intentionally a no-op.
-
- Once the scrub gate blocks a wrong-language answer, the replacement must
- therefore travel through the adapter's trusted prompt capability; otherwise
- the turn waits forever and the next utterance inherits the interrupt state.
- """
- session, _provider, wire, surface = await _open_call()
- wrong_pcm = _pcm(value=700)
- correct_pcm = _pcm(value=1300)
- try:
- since = surface.mark()
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(
- type="input_transcript",
- text="What is kindness?",
- is_final=True,
- ),
- RealtimeEvent(
- type="audio_delta",
- audio=AudioChunk(
- pcm=wrong_pcm,
- sample_rate=OUTPUT_RATE,
- timestamp_ns=0,
- ),
- ),
- RealtimeEvent(
- type="output_transcript_delta",
- text=(
- "Esta es una respuesta completa en español con suficientes "
- "palabras para identificar claramente el idioma."
- ),
- ),
- RealtimeEvent(type="turn_complete"),
- )
-
- await asyncio.wait_for(wire.text_appended.wait(), TIMEOUT_S)
- assert "English" in wire.texts[-1]
- assert wire.response_requests == 1, (
- "the dead automatic-response request was used for the retry"
- )
- assert surface.binary == [], "blocked wrong-language PCM reached playback"
-
- wire.push(
- RealtimeEvent(
- type="output_transcript_delta",
- text=(
- "Kindness means treating other people with consistent care "
- "and respect."
- ),
- ),
- RealtimeEvent(
- type="audio_delta",
- audio=AudioChunk(
- pcm=correct_pcm,
- sample_rate=OUTPUT_RATE,
- timestamp_ns=0,
- ),
- ),
- RealtimeEvent(type="turn_complete"),
- )
- await surface.wait_json(
- lambda message: message.get("type") == "turn_complete",
- since=since,
- )
-
- assert surface.binary == [correct_pcm]
- await _assert_at_rest(session, wire, note="after a prompted language retry")
- finally:
- await _end(session)
-
-
-# -- the headline case ------------------------------------------------------
-
-
-async def test_three_consecutive_turns_each_answer_and_leave_the_call_listening() -> (
- None
-):
- """The maintainer's report, as a test: works once, then only listens.
-
- Three turns, and after each one the call must be genuinely at rest AND
- still able to hear the microphone.
- """
- session, _provider, wire, surface = await _open_call()
- try:
- for index in (1, 2, 3):
- await _run_turn(session, wire, surface, index)
- await _assert_at_rest(session, wire, note=f"after turn {index}")
-
- spoken = [
- message
- for message in surface.json
- if message.get("type") == "transcript"
- and message.get("role") == "assistant"
- ]
- assert [m["text"] for m in spoken] == [_answer(1), _answer(2), _answer(3)]
- heard = [
- message
- for message in surface.json
- if message.get("type") == "transcript"
- and message.get("role") == "user"
- and message.get("is_final")
- ]
- assert [m["text"] for m in heard] == [
- _question(1),
- _question(2),
- _question(3),
- ]
- assert len(surface.binary) == 6 # two audio frames per turn, all played
- finally:
- await _end(session)
-
-
-async def test_every_turn_after_the_first_is_still_transcribed() -> None:
- """Turn 2 and 3 must reach the surface, not just turn 1.
-
- A latched flag, a consumed generator, or a duplicate-item guard that never
- resets all present the same way: turn 1 is perfect and nothing else is.
- """
- session, _provider, wire, surface = await _open_call()
- try:
- for index in (1, 2, 3):
- since = surface.mark()
- wire.push(*_turn_events(index))
- heard = await surface.wait_json(
- lambda m: m.get("type") == "transcript"
- and m.get("role") == "user"
- and m.get("is_final"),
- since=since,
- )
- assert heard["text"] == _question(index)
- await surface.wait_json(
- lambda m: m.get("type") == "turn_complete", since=since
- )
- finally:
- await _end(session)
-
-
-# -- adversarial turns ------------------------------------------------------
-
-
-async def test_a_reply_split_by_a_long_internal_pause_stays_one_answer() -> None:
- """A pause longer than the adapter's quiescence window, as the session sees it.
-
- The backstop that ends a turn on silence lives in the adapter, so what
- reaches the session is a turn boundary mid-reply followed by the REST of
- the same answer. The call must absorb that and stay listening rather than
- leaving the second half stranded in a turn that never closes.
- """
- session, _provider, wire, surface = await _open_call()
- try:
- since = surface.mark()
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(type="input_transcript", text="tell me a long one", is_final=True),
- RealtimeEvent(type="output_transcript_delta", text="First half."),
- RealtimeEvent(type="audio_delta", audio=_audio()),
- # The quiescence backstop fires inside the reply.
- RealtimeEvent(type="turn_complete"),
- )
- await surface.wait_json(lambda m: m.get("type") == "turn_complete", since=since)
-
- # ...and the rest of the same answer arrives afterwards.
- second = surface.mark()
- wire.push(
- RealtimeEvent(type="output_transcript_delta", text="Second half."),
- RealtimeEvent(type="audio_delta", audio=_audio()),
- RealtimeEvent(type="turn_complete"),
- )
- await surface.wait_json(lambda m: m.get("type") == "turn_complete", since=second)
- await _assert_at_rest(session, wire, note="after a split reply")
-
- # And a genuinely new turn still works.
- await _run_turn(session, wire, surface, 2)
- await _assert_at_rest(session, wire, note="after the turn following a split reply")
- finally:
- await _end(session)
-
-
-async def test_a_turn_without_any_terminal_item_does_not_wedge_the_next_one(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """ChatGPT-Live's terminal response item is not guaranteed to arrive.
-
- When it does not, the turn never closes - and under half duplex the
- microphone stays muted, so the user is talking into a session that cannot
- hear them. The next genuine utterance must still land, which means the
- session has to own an unmute path instead of trusting the provider to send
- a well-formed boundary.
-
- The release is deliberately gated on a mute that is BOTH overdue and no
- longer producing audio, so this shortens that window rather than waiting
- out the production value - and a reply still streaming audio keeps its
- microphone shut, which the sibling tests cover.
- """
- monkeypatch.setattr(session_mod, "_HALF_DUPLEX_SILENT_RELEASE_S", 0.05)
- session, _provider, wire, surface = await _open_call()
- try:
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(type="input_transcript", text="no boundary please", is_final=True),
- RealtimeEvent(
- type="output_transcript_delta",
- text=(
- "This is a complete English answer with enough ordinary "
- "words to establish its language, but no terminal boundary."
- ),
- ),
- RealtimeEvent(type="audio_delta", audio=_audio()),
- # No turn_complete, deliberately.
- )
- await surface.wait_binary(at_least=1)
-
- # One frame arms the mute clock; the window then passes with no further
- # provider audio, which is what marks the turn as over.
- await session.handle_audio_frame(_pcm())
- await asyncio.sleep(0.08)
-
- # The next utterance must reach the provider and open its own turn.
- before = len(wire.sent_audio)
- await asyncio.wait_for(session.handle_audio_frame(_pcm()), TIMEOUT_S)
- assert len(wire.sent_audio) > before, (
- "the microphone was still muted by an unterminated turn"
- )
-
- second = surface.mark()
- wire.push(*_turn_events(2))
- await surface.wait_json(lambda m: m.get("type") == "turn_complete", since=second)
- await _assert_at_rest(session, wire, note="after an unterminated turn")
- finally:
- await _end(session)
-
-
-async def test_a_provider_error_closing_a_turn_still_releases_the_microphone(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Scopes MT-1: which non-``turn_complete`` endings DO release the mute.
-
- The adapter ends a turn on an error without a terminal boundary in several
- places (a transport error, a stream that ends). If the session recovers the
- microphone there, MT-1 is narrow; if it does not, half duplex has no
- unmute path at all except a well-behaved provider.
- """
- monkeypatch.setattr(session_mod, "_HALF_DUPLEX_SILENT_RELEASE_S", 0.05)
- session, _provider, wire, surface = await _open_call()
- try:
- since = surface.mark()
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(type="input_transcript", text=_question(1), is_final=True),
- RealtimeEvent(type="output_transcript_delta", text=_answer(1)),
- RealtimeEvent(type="audio_delta", audio=_audio()),
- RealtimeEvent(
- type="error",
- error="Codex subscription realtime transport failed",
- recoverable=True,
- ),
- )
- # A recoverable provider error surfaces as a warning, not a hangup.
- await surface.wait_json(
- lambda m: m.get("type") in {"provider_warning", "error", "turn_complete"},
- since=since,
- )
-
- # One frame arms the mute clock; the window then passes with no further
- # provider audio, which is what marks the turn as over.
- await session.handle_audio_frame(_pcm())
- await asyncio.sleep(0.08)
-
- before = len(wire.sent_audio)
- await asyncio.wait_for(session.handle_audio_frame(_pcm()), TIMEOUT_S)
- assert len(wire.sent_audio) > before, (
- "an error boundary left the microphone muted too - half duplex has "
- "no unmute path that the session itself owns"
- )
- finally:
- await _end(session)
-
-
-async def test_a_provider_that_goes_silent_after_turn_one_keeps_the_call_listening() -> (
- None
-):
- """Turn 1 answers, then the provider says nothing at all, forever.
-
- The call is allowed to be silent. It is NOT allowed to stop accepting the
- microphone: that is the difference between "the model has nothing to say"
- and "the product is wedged".
- """
- session, _provider, wire, surface = await _open_call()
- try:
- await _run_turn(session, wire, surface, 1)
- await _assert_at_rest(session, wire, note="after turn 1")
-
- # Turn 2: the user speaks, the provider never responds.
- since = surface.mark()
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(type="input_transcript", text="anyone there", is_final=True),
- )
- await surface.wait_json(
- lambda m: m.get("type") == "transcript"
- and m.get("role") == "user"
- and m.get("text") == "anyone there",
- since=since,
- )
-
- for _ in range(3):
- before = len(wire.sent_audio)
- await asyncio.wait_for(session.handle_audio_frame(_pcm()), TIMEOUT_S)
- assert len(wire.sent_audio) == before + 1, (
- "a silent provider must not cost the session its microphone"
- )
- finally:
- await _end(session)
-
-
-async def test_a_late_user_transcript_does_not_break_the_turn_in_flight() -> None:
- """The provider's own user transcript trails its audio by seconds.
-
- Arriving after the assistant already started answering, it is a duplicate
- of an utterance that was already grounded — never evidence of a new one. It
- must not strand the reply or the turns after it.
- """
- session, _provider, wire, surface = await _open_call()
- try:
- since = surface.mark()
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(type="input_transcript", text="how are you", is_final=True),
- RealtimeEvent(type="output_transcript_delta", text="I am doing well."),
- RealtimeEvent(type="audio_delta", audio=_audio()),
- # The far end's own copy of the SAME utterance, arriving late.
- RealtimeEvent(type="input_transcript", text="how are you", is_final=True),
- RealtimeEvent(type="turn_complete"),
- )
- await surface.wait_json(lambda m: m.get("type") == "turn_complete", since=since)
- await _assert_at_rest(session, wire, note="after a late duplicate transcript")
-
- await _run_turn(session, wire, surface, 2)
- await _assert_at_rest(session, wire, note="after the turn following a late transcript")
- finally:
- await _end(session)
-
-
-async def test_a_dead_local_recognizer_still_lets_the_assistant_answer() -> None:
- """The grounding evidence source failed; the answer must survive it.
-
- On this transport the local recognizer is the only source of a user
- transcript, so its failure is reported as an empty final transcript with an
- error — exactly what the adapter's missing-input boundary emits. The model
- already heard the audio, so its reply must still reach the user, and the
- call must remain usable.
- """
- session, _provider, wire, surface = await _open_call()
- try:
- since = surface.mark()
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(
- type="input_transcript",
- text="",
- is_final=True,
- error="Local and provider input transcription were unavailable.",
- ),
- RealtimeEvent(type="output_transcript_delta", text="I heard you anyway."),
- RealtimeEvent(type="audio_delta", audio=_audio()),
- RealtimeEvent(type="turn_complete"),
- )
- await surface.wait_json(lambda m: m.get("type") == "turn_complete", since=since)
-
- spoken = [
- message
- for message in surface.json[since:]
- if message.get("type") == "transcript"
- and message.get("role") == "assistant"
- ]
- assert spoken, "the reply was dropped because the recognizer failed"
- assert surface.binary, "the reply's audio never reached the surface"
- assert wire.interrupts == 0, (
- "a dead evidence source must not interrupt the model"
- )
- await _assert_at_rest(session, wire, note="after a failed local recognizer")
-
- await _run_turn(session, wire, surface, 2)
- await _assert_at_rest(session, wire, note="after the turn following a failure")
- finally:
- await _end(session)
-
-
-async def test_a_hanging_close_does_not_stall_the_transport_rebuild(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The dead transport's socket close took its full window live
- (2026-08-06 17:42) - and the rebuild the call was waiting on stalled
- behind it. The close is a courtesy to a corpse: bounded, then abandoned.
- """
- monkeypatch.setattr(session_mod, "_PROVIDER_CLOSE_BOUND_S", 0.2)
-
- class _HangingCloseWire(_CodexShapedWire):
- async def close(self) -> None:
- await asyncio.sleep(30.0)
-
- class _RebuildingProvider(_CodexShapedProvider):
- def __init__(self) -> None:
- super().__init__()
- self.open_count = 0
-
- async def open_session(self, config: Any) -> _CodexShapedWire:
- self.opened_with = config
- self.open_count += 1
- wire = (
- _HangingCloseWire() if self.open_count == 1 else _CodexShapedWire()
- )
- self.sessions.append(wire)
- return wire
-
- surface = _Surface()
- provider = _RebuildingProvider()
- session = RealtimeVoiceSession(
- session_id="rebuild-close-bound",
- send_binary=surface.send_binary,
- send_json=surface.send_json,
- providers=[provider],
- config=_config(),
- bus=EventBus(),
- surface="desktop",
- half_duplex=True,
- browser_sample_rate=INPUT_RATE,
- )
- await asyncio.wait_for(
- session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),
- TIMEOUT_S,
- )
- try:
- first_wire = provider.sessions[0]
- since = surface.mark()
- first_wire.push(
- RealtimeEvent(
- type="error",
- error="transport died",
- recoverable=True,
- reconnect_advised=True,
- ),
- RealtimeEvent(type="turn_complete"),
- )
- # The rebuild must complete despite the corpse's 30 s close: a fresh
- # audio_ready proves the new transport opened.
- ready = await surface.wait_json(
- lambda m: m.get("type") == "audio_ready",
- since=since,
- timeout_s=TIMEOUT_S,
- )
- assert ready is not None
- assert provider.open_count == 2, "a second transport must have opened"
- finally:
- await _end(session)
-
-
-def _session_with_bus(
- name: str,
-) -> tuple[RealtimeVoiceSession, _CodexShapedProvider, _Surface, list[Any]]:
- """A desktop-shaped session whose VoiceTurnCompleted events are captured."""
- from jarvis.core.events import VoiceTurnCompleted
-
- surface = _Surface()
- provider = _CodexShapedProvider()
- bus = EventBus()
- completed: list[Any] = []
-
- async def _collect(event: VoiceTurnCompleted) -> None:
- completed.append(event)
-
- bus.subscribe(VoiceTurnCompleted, _collect)
- session = RealtimeVoiceSession(
- session_id=name,
- send_binary=surface.send_binary,
- send_json=surface.send_json,
- providers=[provider],
- config=_config(),
- bus=bus,
- surface="desktop",
- half_duplex=True,
- browser_sample_rate=INPUT_RATE,
- )
- return session, provider, surface, completed
-
-
-async def _wait_completed(completed: list[Any]) -> None:
- for _ in range(50):
- if completed:
- return
- await asyncio.sleep(0.01)
- raise AssertionError("the turn never published VoiceTurnCompleted")
-
-
-async def test_a_partial_only_turn_promotes_its_preview_explicitly() -> None:
- """A turn whose FINAL never arrives must not silently record a mid-word
- partial as the user's utterance (the recorded "illst.") - the retained
- live caption is promoted, with its own log line, instead."""
- session, provider, surface, completed = _session_with_bus("preview-promote")
- await asyncio.wait_for(
- session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),
- TIMEOUT_S,
- )
- try:
- wire = provider.sessions[0]
- since = surface.mark()
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(
- type="input_transcript",
- text="what color is the vio",
- is_final=False,
- ),
- RealtimeEvent(type="output_transcript_delta", text="Violet."),
- RealtimeEvent(type="audio_delta", audio=_audio()),
- RealtimeEvent(type="turn_complete"),
- )
- await surface.wait_json(
- lambda m: m.get("type") == "turn_complete", since=since
- )
- await _wait_completed(completed)
- assert completed[0].user_text == "what color is the vio", (
- "the preview is promoted - explicitly - when no final arrived"
- )
- finally:
- await _end(session)
-
-
-async def test_a_refinalized_item_replaces_instead_of_doubling() -> None:
- """A provider re-finalizing the same input item (a correction) must not
- concatenate the utterance into itself."""
- session, provider, surface, completed = _session_with_bus("refinal-replace")
- await asyncio.wait_for(
- session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),
- TIMEOUT_S,
- )
- try:
- wire = provider.sessions[0]
- since = surface.mark()
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(
- type="input_transcript",
- text="what color is the giraffe",
- is_final=True,
- item_id="item-1",
- ),
- RealtimeEvent(
- type="input_transcript",
- text="what color is the violet giraffe",
- is_final=True,
- item_id="item-1",
- ),
- RealtimeEvent(type="output_transcript_delta", text="Violet."),
- RealtimeEvent(type="audio_delta", audio=_audio()),
- RealtimeEvent(type="turn_complete"),
- )
- await surface.wait_json(
- lambda m: m.get("type") == "turn_complete", since=since
- )
- await _wait_completed(completed)
- assert completed[0].user_text == "what color is the violet giraffe", (
- "the re-final replaces its item instead of double-booking it"
- )
- finally:
- await _end(session)
-
-
-async def test_a_partial_never_flips_the_call_language() -> None:
- """Language resolution runs on FINALS only: a growing caption used to
- flip the call language (and rebuild the scrub gate) mid-utterance."""
- session, provider, surface, _completed = _session_with_bus("partial-lang")
- await asyncio.wait_for(
- session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),
- TIMEOUT_S,
- )
- try:
- wire = provider.sessions[0]
- opening_language = session._language # noqa: SLF001
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(
- type="input_transcript",
- # A decidedly German partial on an English-opened call.
- text="wie viele Raeder hat das erfundene Fahrrad denn nun",
- is_final=False,
- ),
- )
- await asyncio.sleep(0.15)
- assert session._language == opening_language, ( # noqa: SLF001
- "a partial flipped the call language"
- )
- finally:
- await _end(session)
-
-
-async def test_a_thin_first_fragment_does_not_set_the_call_language() -> None:
- """A misheard 328 ms fragment ("Mask it up!") flipped a German call to
- English AND stuck. Before the conversation is established, a final under
- the voiced-duration floor resolves without its unreliable words; the
- first substantive final then establishes the language for real."""
- session, provider, surface, _completed = _session_with_bus("thin-fragment")
- await asyncio.wait_for(
- session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),
- TIMEOUT_S,
- )
- try:
- wire = provider.sessions[0]
- opening_language = session._language # noqa: SLF001
- since = surface.mark()
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(
- type="input_transcript",
- text="Mask it up!",
- is_final=True,
- voiced_ms=328,
- ),
- RealtimeEvent(type="output_transcript_delta", text="Hey!"),
- RealtimeEvent(type="audio_delta", audio=_audio()),
- RealtimeEvent(type="turn_complete"),
- )
- await surface.wait_json(
- lambda m: m.get("type") == "turn_complete", since=since
- )
- assert session._language == opening_language, ( # noqa: SLF001
- "a 328 ms misheard fragment set the call language"
- )
- assert session._conversation_established is False # noqa: SLF001
-
- # The first SUBSTANTIVE final establishes the language for real.
- since = surface.mark()
- wire.push(
- RealtimeEvent(type="speech_started"),
- RealtimeEvent(
- type="input_transcript",
- text="Wie viele Raeder hat mein erfundenes Fahrrad? Bitte sag es mir.",
- is_final=True,
- voiced_ms=2100,
- ),
- RealtimeEvent(type="output_transcript_delta", text="Fuenf."),
- RealtimeEvent(type="audio_delta", audio=_audio()),
- RealtimeEvent(type="turn_complete"),
- )
- await surface.wait_json(
- lambda m: m.get("type") == "turn_complete", since=since
- )
- assert session._conversation_established is True # noqa: SLF001
- finally:
- await _end(session)
diff --git a/tests/unit/brain/test_current_model_catalogs.py b/tests/unit/brain/test_current_model_catalogs.py
index d9d44ac7fe..40d7846c78 100644
--- a/tests/unit/brain/test_current_model_catalogs.py
+++ b/tests/unit/brain/test_current_model_catalogs.py
@@ -126,20 +126,9 @@ def test_current_stt_and_cartesia_model_rosters() -> None:
def test_current_realtime_models_and_voices() -> None:
- # ChatGPT-Live (v3) picks the model server-side — one honest entry, no
- # fake choice (client model fields are rejected; verified 2026-08-01).
- assert _ids(REALTIME_MODELS["codex-subscription-realtime"]) == {"auto"}
- assert _ids(REALTIME_VOICES["codex-subscription-realtime"]) == {
- "cove",
- "juniper",
- "maple",
- "spruce",
- "ember",
- "vale",
- "breeze",
- "arbor",
- "sol",
- }
+ # codex-subscription-realtime was removed 2026-08-10 with its adapter.
+ assert "codex-subscription-realtime" not in REALTIME_MODELS
+ assert "codex-subscription-realtime" not in REALTIME_VOICES
assert {
"gpt-realtime",
"gpt-realtime-mini",
diff --git a/tests/unit/brain/test_model_catalog.py b/tests/unit/brain/test_model_catalog.py
index 3ea45ba05d..3f603312c0 100644
--- a/tests/unit/brain/test_model_catalog.py
+++ b/tests/unit/brain/test_model_catalog.py
@@ -754,25 +754,12 @@ class TestModelClassification:
class TestRealtimeCatalog:
- def test_codex_subscription_catalog_matches_app_server_v3(self) -> None:
+ def test_removed_codex_subscription_catalog_is_gone(self) -> None:
+ """codex-subscription-realtime was removed 2026-08-10 with its adapter."""
from jarvis.brain.model_catalog import REALTIME_MODELS, REALTIME_VOICES
- # v3 (ChatGPT-Live): the server chooses the model; the voice roster
- # below is the server-confirmed nine (verified live 2026-08-01).
- assert [m.id for m in REALTIME_MODELS["codex-subscription-realtime"]] == [
- "auto"
- ]
- assert [v.id for v in REALTIME_VOICES["codex-subscription-realtime"]] == [
- "cove",
- "juniper",
- "maple",
- "spruce",
- "ember",
- "vale",
- "breeze",
- "arbor",
- "sol",
- ]
+ assert "codex-subscription-realtime" not in REALTIME_MODELS
+ assert "codex-subscription-realtime" not in REALTIME_VOICES
def test_openai_realtime_models_lead_with_the_hardcoded_default(self) -> None:
from jarvis.brain.model_catalog import REALTIME_MODELS
diff --git a/tests/unit/commands/test_registry_parity.py b/tests/unit/commands/test_registry_parity.py
index 39cda085a0..f9f631a588 100644
--- a/tests/unit/commands/test_registry_parity.py
+++ b/tests/unit/commands/test_registry_parity.py
@@ -142,7 +142,9 @@ def test_realtime_switch_exposes_experimental_acknowledgement() -> None:
command = get_command("realtime-switch")
assert command is not None
properties = command.params["properties"]
- assert "codex-subscription-realtime" in properties["provider"]["enum"]
+ # Removed 2026-08-10 with its adapter — the enum must not offer it.
+ assert "codex-subscription-realtime" not in properties["provider"]["enum"]
+ assert "openai-realtime" in properties["provider"]["enum"]
assert properties["accept_experimental"] == {
"type": "boolean",
"default": False,
diff --git a/tests/unit/core/test_voice_mode_config.py b/tests/unit/core/test_voice_mode_config.py
index 8a1a9983fe..cd485da05d 100644
--- a/tests/unit/core/test_voice_mode_config.py
+++ b/tests/unit/core/test_voice_mode_config.py
@@ -85,14 +85,17 @@ def test_realtime_voice_selection_persists_all_three_values_once(
assert 'mode = "realtime"' in content
-def test_load_config_repairs_already_active_legacy_codex_realtime_state(
+def test_load_config_migrates_removed_codex_realtime_primary(
tmp_path: Path,
monkeypatch,
):
+ """A config still pinning the removed codex-subscription-realtime adapter
+ boots onto the stable subscription composition instead of a dead
+ Realtime mode (adapter removed 2026-08-10)."""
toml = tmp_path / "jarvis.toml"
toml.write_text(
'[brain.realtime]\nprovider = "codex-subscription-realtime"\n\n'
- '[voice]\nmode = "pipeline"\nprofile = "codex-subscription-voice"\n',
+ '[voice]\nmode = "realtime"\nprofile = ""\n',
encoding="utf-8",
)
monkeypatch.setattr(cfg_mod, "resolve_config_path", lambda: toml)
@@ -101,12 +104,33 @@ def test_load_config_repairs_already_active_legacy_codex_realtime_state(
loaded = cfg_mod.load_config()
assert loaded.brain.realtime is not None
- assert loaded.brain.realtime.provider == "codex-subscription-realtime"
- assert loaded.voice.mode == "realtime"
- assert loaded.voice.profile == ""
+ assert loaded.brain.realtime.provider == ""
+ assert loaded.voice.mode == "pipeline"
+ assert loaded.voice.profile == "codex-subscription-voice"
content = toml.read_text(encoding="utf-8")
- assert 'mode = "realtime"' in content
- assert 'profile = ""' in content
+ assert 'provider = ""' in content
+ assert 'mode = "pipeline"' in content
+ assert 'profile = "codex-subscription-voice"' in content
+
+
+def test_load_config_leaves_other_realtime_selections_untouched(
+ tmp_path: Path,
+ monkeypatch,
+):
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text(
+ '[brain.realtime]\nprovider = "openai-realtime"\n\n'
+ '[voice]\nmode = "realtime"\nprofile = ""\n',
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(cfg_mod, "resolve_config_path", lambda: toml)
+ cfg_mod._LEGACY_CODEX_REALTIME_HEALED.discard(toml)
+
+ loaded = cfg_mod.load_config()
+
+ assert loaded.brain.realtime is not None
+ assert loaded.brain.realtime.provider == "openai-realtime"
+ assert loaded.voice.mode == "realtime"
def test_realtime_tier_field_accepts_brain_tier_config():
diff --git a/tests/unit/diagnostics/test_realtime_probe_eval.py b/tests/unit/diagnostics/test_realtime_probe_eval.py
deleted file mode 100644
index 4d134ba985..0000000000
--- a/tests/unit/diagnostics/test_realtime_probe_eval.py
+++ /dev/null
@@ -1,220 +0,0 @@
-"""The probe's scenario judge, exercised without any live call.
-
-``evaluate_scenario`` is pure over the capture rows + postmortem, so every
-assert's pass/fail boundary is pinned here — the live integration test then
-only has to trust one judgment path, not two.
-"""
-
-from __future__ import annotations
-
-from typing import Any
-
-from jarvis.diagnostics.realtime_probe import (
- CONTINUITY_GAP_S,
- evaluate_scenario,
-)
-
-MANIFEST = [
- {
- "id": "en_giraffe",
- "text": "What color is the violet giraffe from my example? Answer in one short sentence.",
- "nonce": "violet giraffe",
- "language": "en",
- },
-]
-
-
-def _row(mono: float, src: str, kind: str, data: dict[str, Any]) -> dict[str, Any]:
- return {"ts": mono, "mono": mono, "src": src, "kind": kind, "data": data}
-
-
-def _transcript(mono: float, role: str, text: str, *, final: bool = True) -> dict[str, Any]:
- return _row(
- mono,
- "surface",
- "json",
- {"type": "transcript", "role": role, "text": text, "is_final": final},
- )
-
-
-def _happy_rows() -> list[dict[str, Any]]:
- rows = [
- _row(0.0, "probe", "scenario", {"name": "t"}),
- _row(1.0, "probe", "ready", {"type": "audio_ready"}),
- _row(2.0, "probe", "speak", {"id": "en_giraffe"}),
- _transcript(4.0, "user", "what color is the violet giraffe"),
- ]
- # A contiguous reply: chunks 100 ms apart, each carrying 100 ms of audio.
- mono = 5.0
- for _ in range(10):
- rows.append(_row(mono, "surface", "binary", {"bytes": 4800}))
- mono += 0.1
- rows.append(_transcript(mono, "assistant", "It is violet."))
- rows.append(_row(mono + 0.2, "surface", "json", {"type": "turn_complete"}))
- return rows
-
-
-def test_a_final_that_trails_its_boundary_still_grounds_it() -> None:
- """Live round 1: the recognizer's round trip regularly lands the user
- FINAL seconds after the turn's boundary. Grounding must tolerate the
- trail, or every healthy call reads as self-talk."""
- rows = [
- _row(1.0, "probe", "ready", {"type": "audio_ready"}),
- _transcript(4.0, "assistant", "It is violet."),
- _row(5.0, "surface", "json", {"type": "turn_complete"}),
- _transcript(6.5, "user", "what color is the violet giraffe"),
- _transcript(7.0, "assistant", "Still violet."),
- ]
- verdict = _judge(rows, _pm(), ["no_ungrounded"])["no_ungrounded"]
- assert verdict["status"] == "pass", verdict
-
-
-def _pm(**overrides: Any) -> dict[str, Any]:
- base: dict[str, Any] = {
- "turns_completed": 1,
- "rebuilds": 0,
- "stun_retries": 0,
- "recv_dropped_frames": 0,
- "sender_pacing_resyncs": 0,
- "sender_shed_frames": 0,
- "ready_ms": 2500,
- "first_audio_ms": 4200,
- "close_clean": True,
- }
- base.update(overrides)
- return base
-
-
-def _judge(
- rows: list[dict[str, Any]],
- pm: dict[str, Any],
- asserts: list[str],
- *,
- budgets: dict[str, Any] | None = None,
- end_duration_s: float = 1.0,
-) -> dict[str, dict[str, str]]:
- return evaluate_scenario(
- rows,
- pm,
- {"name": "t", "asserts": asserts},
- MANIFEST,
- budgets=budgets or {},
- end_duration_s=end_duration_s,
- )
-
-
-def test_happy_path_passes_everything() -> None:
- verdicts = _judge(
- _happy_rows(),
- _pm(),
- [
- "turns>=1",
- "no_ungrounded",
- "no_roleplay",
- "audio_continuity",
- "no_rebuilds",
- "mic_wall_clock",
- "spawn_budget",
- "clean_close",
- ],
- )
- assert all(v["status"] == "pass" for v in verdicts.values()), verdicts
-
-
-def test_missing_turn_fails_the_count() -> None:
- rows = _happy_rows()
- verdicts = _judge(rows, _pm(), ["turns>=2"])
- assert verdicts["turns>=2"]["status"] == "fail"
-
-
-def test_ungrounded_greeting_is_allowed_even_when_its_boundary_lands_late() -> None:
- """Live round 1: the greeting monologue STARTED right at ready but ran
- 16+ s, so its boundary fell far outside any window anchored on ready.
- The allowance keys on when the boundary's speech began."""
- rows = [
- _row(1.0, "probe", "ready", {"type": "audio_ready"}),
- _transcript(2.0, "assistant", "Hey there, ready when you are."),
- # ... it rambles; the boundary only lands 17 s after ready ...
- _row(18.0, "surface", "json", {"type": "turn_complete"}),
- _transcript(20.0, "user", "what color is the violet giraffe"),
- _transcript(21.0, "assistant", "Violet."),
- _row(22.0, "surface", "json", {"type": "turn_complete"}),
- ]
- assert _judge(rows, _pm(), ["no_ungrounded"])["no_ungrounded"]["status"] == "pass"
-
- # A SECOND ungrounded turn, speech starting long past the window: fails.
- rows += [
- _transcript(29.0, "assistant", "Anyway, as I was saying to myself."),
- _row(31.0, "surface", "json", {"type": "turn_complete"}),
- ]
- assert _judge(rows, _pm(), ["no_ungrounded"])["no_ungrounded"]["status"] == "fail"
-
-
-def test_roleplay_detects_the_full_question_but_not_the_topic() -> None:
- rows = _happy_rows()
- # Answering with the nonce topic is legitimate.
- assert _judge(rows, _pm(), ["no_roleplay"])["no_roleplay"]["status"] == "pass"
- # Speaking the user's full question verbatim is the both-sides signature.
- rows.append(
- _transcript(
- 9.0,
- "assistant",
- "Hi! What color is the violet giraffe from my example? "
- "Answer in one short sentence. Well, violet!",
- )
- )
- assert _judge(rows, _pm(), ["no_roleplay"])["no_roleplay"]["status"] == "fail"
-
-
-def test_selftalk_on_a_silent_microphone_fails() -> None:
- rows = [
- _row(1.0, "probe", "ready", {"type": "audio_ready"}),
- _transcript(20.0, "assistant", "Hey. Hi, what's up?", final=False),
- ]
- assert _judge(rows, _pm(), ["no_selftalk"])["no_selftalk"]["status"] == "fail"
- early = [
- _row(1.0, "probe", "ready", {"type": "audio_ready"}),
- _transcript(4.0, "assistant", "Hey!", final=False),
- ]
- assert _judge(early, _pm(), ["no_selftalk"])["no_selftalk"]["status"] == "pass"
-
-
-def test_audio_hole_beyond_the_gap_budget_fails_continuity() -> None:
- rows = _happy_rows()
- verdict = _judge(rows, _pm(), ["audio_continuity"])["audio_continuity"]
- assert verdict["status"] == "pass"
- # Inject a hole: the next chunk arrives seconds late inside the same turn.
- late = _happy_rows()
- hole_at = late[-3]["mono"] + CONTINUITY_GAP_S + 1.0
- late.insert(-2, _row(hole_at, "surface", "binary", {"bytes": 4800}))
- assert _judge(late, _pm(), ["audio_continuity"])["audio_continuity"]["status"] == "fail"
-
-
-def test_postmortem_counters_gate_their_asserts() -> None:
- rows = _happy_rows()
- assert _judge(rows, _pm(rebuilds=1), ["no_rebuilds"])["no_rebuilds"]["status"] == "fail"
- assert (
- _judge(rows, _pm(sender_shed_frames=3), ["mic_wall_clock"])["mic_wall_clock"]["status"]
- == "fail"
- )
- assert (
- _judge(rows, _pm(close_clean=False), ["clean_close"])["clean_close"]["status"]
- == "fail"
- )
- assert (
- _judge(rows, _pm(), ["clean_close"], end_duration_s=30.0)["clean_close"]["status"]
- == "fail"
- )
-
-
-def test_spawn_budget_warns_until_enforced() -> None:
- rows = _happy_rows()
- slow = _pm(ready_ms=9000)
- assert _judge(rows, slow, ["spawn_budget"])["spawn_budget"]["status"] == "warn"
- enforced = _judge(rows, slow, ["spawn_budget"], budgets={"enforce": True})
- assert enforced["spawn_budget"]["status"] == "fail"
-
-
-def test_unknown_assert_is_a_scenario_bug() -> None:
- verdicts = _judge(_happy_rows(), _pm(), ["definitely_not_a_check"])
- assert verdicts["definitely_not_a_check"]["status"] == "fail"
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
deleted file mode 100644
index 1a78c29305..0000000000
--- a/tests/unit/realtime/test_codex_subscription.py
+++ /dev/null
@@ -1,4134 +0,0 @@
-"""Codex ChatGPT-subscription realtime adapter and SDP broker tests."""
-
-from __future__ import annotations
-
-import asyncio
-import contextlib
-import logging
-from types import SimpleNamespace
-
-import pytest
-
-import jarvis.plugins.realtime.codex_subscription as codex_subscription_mod
-from jarvis.codex_app_server import _MAX_REALTIME_INITIAL_TEXT_BYTES
-from jarvis.plugins.realtime.codex_subscription import (
- CodexSubscriptionRealtimeProvider,
-)
-from jarvis.realtime.input_transcription import InputTranscriptEvent
-from jarvis.realtime.offer_broker import RealtimeTransportOfferBroker
-from jarvis.realtime.protocol import RealtimeSessionConfig
-
-
-class _Notification:
- def __init__(self, method: str, params: dict) -> None:
- self.method = method
- self.params = params
-
-
-class _Subscription:
- def __init__(self, events=(), *, failure: BaseException | None = None) -> None:
- self.events = list(events)
- self.failure = failure
- self.closed = False
-
- def __aiter__(self):
- return self
-
- async def __anext__(self):
- if self.failure is not None:
- failure = self.failure
- self.failure = None
- raise failure
- if not self.events:
- raise StopAsyncIteration
- return self.events.pop(0)
-
- def close(self) -> None:
- self.closed = True
-
-
-class _ScheduledSubscription(_Subscription):
- def __init__(self, scheduled_events) -> None:
- super().__init__()
- self.scheduled_events = list(scheduled_events)
-
- async def __anext__(self):
- if not self.scheduled_events:
- raise StopAsyncIteration
- delay_s, event = self.scheduled_events.pop(0)
- if delay_s:
- await asyncio.sleep(delay_s)
- return event
-
-
-class _CountingSubscription(_Subscription):
- def __init__(self) -> None:
- super().__init__()
- self.yielded = 0
-
- async def __anext__(self):
- self.yielded += 1
- return _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "user",
- "delta": str(self.yielded),
- },
- )
-
-
-class _FakeAudioEndpoint:
- """Stands in for the in-process WebRTC peer.
-
- ChatGPT-Live carries audio on the media track, so the adapter owns a real
- peer in production. Tests inject this to keep the suite off the network
- while still pinning that microphone PCM reaches the media path and that
- remote audio re-enters the normalized event stream.
- """
-
- def __init__(
- self,
- *,
- output_chunks: tuple[bytes, ...] = (),
- output_schedule: tuple[tuple[float, bytes], ...] = (),
- ) -> None:
- self.sent: list[tuple[bytes, int]] = []
- self.answers: list[str] = []
- self.closed = False
- self.connected = False
- # ``output_schedule`` paces chunks like real RTP arrival, which is what
- # the quiescence timer reacts to.
- self._schedule = list(output_schedule)
- self._outputs = asyncio.Queue()
- for chunk in output_chunks:
- self._outputs.put_nowait(chunk)
-
- async def create_offer(self) -> str:
- return "v=0\r\no=python-peer\r\n"
-
- async def apply_answer(self, answer_sdp: str) -> None:
- self.answers.append(answer_sdp)
-
- async def wait_connected(self, timeout_s: float = 15.0) -> None:
- del timeout_s
- self.connected = True
-
- def send_pcm(self, pcm: bytes, sample_rate: int) -> None:
- self.sent.append((pcm, sample_rate))
-
- async def next_output_pcm(self):
- if self._schedule:
- delay, chunk = self._schedule.pop(0)
- if delay:
- await asyncio.sleep(delay)
- return chunk
- return await self._outputs.get()
-
- async def close(self) -> None:
- self.closed = True
-
-
-def _provider(client, **kwargs):
- """Build the provider with an injected fake media endpoint."""
- endpoint = kwargs.pop("endpoint", None) or _FakeAudioEndpoint()
- # Adapter tests do not reach the user's configured cloud/local STT unless
- # a case injects an explicit recognizer. The production default is covered
- # by the input-transcriber unit tests.
- kwargs.setdefault("input_transcriber_factory", lambda: None)
- provider = CodexSubscriptionRealtimeProvider(
- client=client,
- # The factory receives the ICE configuration for this attempt.
- audio_endpoint_factory=lambda _ice=None: endpoint,
- **kwargs,
- )
- provider.test_endpoint = endpoint
- return provider
-
-
-class _Client:
- def __init__(
- self,
- events=(),
- *,
- failure: BaseException | None = None,
- start_response: dict | None = None,
- ) -> None:
- self.subscription = _Subscription(events, failure=failure)
- self.thread_starts: list[dict] = []
- self.realtime_starts: list[tuple[str, dict]] = []
- self.audio_appends: list[tuple[str, dict]] = []
- self.text_appends: list[tuple[str, str, str]] = []
- self.speech_appends: list[tuple[str, str]] = []
- self.stops: list[str] = []
- self.interrupts: list[tuple[str, str]] = []
- self.unsubscribes: list[str] = []
- self.poison_calls = 0
- self.capability_calls = 0
- self._thread_number = 0
- self.start_response = dict(start_response or {})
-
- async def capability_status(self):
- self.capability_calls += 1
- return SimpleNamespace(
- available=True,
- chatgpt_authenticated=True,
- reason="",
- )
-
- async def thread_start(self, **kwargs):
- self.thread_starts.append(kwargs)
- self._thread_number += 1
- return {"thread": {"id": f"thread-{self._thread_number}"}}
-
- def subscribe(self, thread_id: str):
- del thread_id
- return self.subscription
-
- async def realtime_start(self, thread_id: str, **kwargs):
- self.realtime_starts.append((thread_id, kwargs))
- return SimpleNamespace(
- response=self.start_response,
- answer_sdp="v=0\r\nanswer",
- )
-
- async def realtime_append_audio(self, thread_id: str, **kwargs):
- self.audio_appends.append((thread_id, kwargs))
- return {}
-
- async def realtime_append_text(self, thread_id: str, text: str, *, role: str = "user"):
- self.text_appends.append((thread_id, text, role))
- return {}
-
- async def realtime_append_speech(self, thread_id: str, text: str):
- self.speech_appends.append((thread_id, text))
- return {}
-
- async def turn_interrupt(self, thread_id: str, turn_id: str):
- self.interrupts.append((thread_id, turn_id))
- return {}
-
- async def realtime_stop(self, thread_id: str):
- self.stops.append(thread_id)
- return {}
-
- async def thread_unsubscribe(self, thread_id: str):
- self.unsubscribes.append(thread_id)
- return {}
-
- async def poison(self) -> None:
- self.poison_calls += 1
-
-
-class _NoOfferBroker:
- async def acquire(self, *, timeout_s: float):
- del timeout_s
- return None
-
-
-class _UnauthenticatedClient(_Client):
- async def thread_start(self, **kwargs):
- self.thread_starts.append(kwargs)
- raise RuntimeError("Codex app-server rejected the unauthenticated account")
-
-
-class _FailedCleanupClient(_Client):
- async def realtime_stop(self, thread_id: str):
- self.stops.append(thread_id)
- raise RuntimeError("stop failed")
-
-
-class _TimedOutCleanupClient(_Client):
- async def realtime_stop(self, thread_id: str):
- self.stops.append(thread_id)
- await asyncio.sleep(60)
-
-
-async def test_direct_sdp_open_uses_safe_experimental_transport_contract() -> None:
- client = _Client()
- provider = _provider(client)
-
- session = await provider.open_session(
- RealtimeSessionConfig(
- instructions="Speak concise English.",
- transport_offer_sdp="v=0\r\no=browser-offer",
- )
- )
-
- assert session.answer_sdp == "v=0\r\nanswer"
- assert client.capability_calls == 0
- assert len(client.thread_starts) == 1
- thread_start = client.thread_starts[0]
- assert thread_start["ephemeral"] is True
- assert "extra" not in thread_start
- # The execution boundary is the security invariant: the Codex agent is
- # the VOICE, never the executor — every action goes out as a handoff.
- base = thread_start["base_instructions"].lower()
- developer = thread_start["developer_instructions"].lower()
- assert "never run tools" in base
- assert "handoff" in base
- assert "do not call tools" in developer
- assert "filesystem" in developer
- # …but it must no longer be told it is a dumb pipe: without an identity
- # the voice knew nothing about its own project.
- assert "persona" in base
-
- # Persona, language policy, and history are part of the atomic live start.
- # No developer append exists for the far end to acknowledge before the
- # user speaks.
- assert client.text_appends == []
- _thread_id, start = client.realtime_starts[0]
- assert start["output_modality"] == "audio"
- assert start["offer_sdp"] == "v=0\r\no=python-peer\r\n"
- assert start["prompt"] == ""
- assert start["initial_items"] == []
- assert start["model"] is None
- assert start["voice"] == "cove"
- assert start["version"] == "v3"
- assert start["include_startup_context"] is False
- assert start["client_managed_handoffs"] is True
- trusted_prompt = start["trusted_prompt"]
- assert "Speak concise English." in trusted_prompt
- assert "Speak only the assistant side" in trusted_prompt
- assert "Reply in the language the user actually speaks" in trusted_prompt
- assert "reply only in" not in trusted_prompt, "a hint is not a pin"
- await session.close()
- assert client.unsubscribes == ["thread-1"]
-
-
-async def test_reopened_session_restores_bounded_same_call_history() -> None:
- client = _Client()
- provider = _provider(client)
- history = (
- {"role": "user", "text": "Which language were we discussing?"},
- {"role": "assistant", "text": "We were discussing Malbolge."},
- )
-
- session = await provider.open_session(
- RealtimeSessionConfig(
- instructions="Speak concise English.",
- history=history,
- )
- )
-
- assert client.text_appends == []
- _thread_id, start = client.realtime_starts[0]
- assert start["initial_items"] == list(history)
- assert "Speak concise English." in start["trusted_prompt"]
- assert "Reply in the language the user actually speaks" in start["trusted_prompt"]
- await session.close()
-
-
-async def test_failed_remote_cleanup_poisons_the_entire_app_server_client() -> None:
- client = _FailedCleanupClient()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- await session.close()
-
- assert client.stops == ["thread-1"]
- assert client.unsubscribes == ["thread-1"]
- assert client.poison_calls == 1
-
-
-async def test_timed_out_remote_cleanup_poisons_the_entire_client(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(codex_subscription_mod, "_REMOTE_CLEANUP_TIMEOUT_S", 0.01)
- client = _TimedOutCleanupClient()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- await session.close()
-
- assert client.unsubscribes == ["thread-1"]
- assert client.poison_calls == 1
-
-
-async def test_stale_api_voice_selection_fails_before_subscription_realtime_start() -> None:
- """A voice outside the server-confirmed v3 roster fails before start."""
- client = _Client()
- provider = _provider(client)
- config = RealtimeSessionConfig(
- transport_offer_sdp="v=0\r\no=browser-offer",
- voice="marin",
- )
-
- with pytest.raises(RuntimeError, match="unsupported voice"):
- await provider.open_session(config)
-
- assert client.realtime_starts == []
- assert client.stops == ["thread-1"]
- assert client.unsubscribes == ["thread-1"]
-
-
-async def test_stale_model_pin_is_ignored_not_fatal() -> None:
- """v3 chooses the model server-side: a leftover pin from the metered API
- (or the dead v1 era) must not brick the call — it is dropped, and no
- model field reaches the server."""
- client = _Client()
- provider = _provider(client)
- config = RealtimeSessionConfig(
- transport_offer_sdp="v=0\r\no=browser-offer",
- model="gpt-4o-realtime-preview",
- )
-
- session = await provider.open_session(config)
-
- assert len(client.realtime_starts) == 1
- _thread, start = client.realtime_starts[0]
- assert start["model"] is None
- assert start["version"] == "v3"
- await session.close()
-
-
-async def test_language_update_is_developer_context_and_speech_is_authoritative() -> None:
- client = _Client()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- await session.update_session(language="es")
- await session.send_speech("Trusted answer")
-
- appended = [text for _thread, text, _role in client.text_appends]
- # The opening hint was atomic startup configuration; the only append is
- # the first real per-turn pin resolved upstream.
- assert appended == [codex_subscription_mod._language_pin_text("es")]
- assert client.speech_appends == [("thread-1", "Trusted answer")]
- await session.close()
-
-
-async def test_context_refresh_appends_only_the_changed_lines() -> None:
- """An append-only transport must not receive the full block per turn.
-
- The session refreshes its ~20k-char instruction block on every final
- user transcript (the clock line alone changes every minute); re-appending
- all of it grew the live thread by a whole persona per exchange.
- """
- client = _Client()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(instructions="Persona line.\nClock: 12:00.")
- )
-
- await session.update_session(instructions="Persona line.\nClock: 12:01.")
-
- context_appends = [
- text
- for _thread, text, role in client.text_appends
- if role == "developer" and ("Persona line." in text or "Clock" in text)
- ]
- assert len(context_appends) == 1
- update = context_appends[0]
- assert "Clock: 12:01." in update
- assert "Persona line." not in update
- assert "stay in force" in update
- await session.close()
-
-
-async def test_per_turn_update_travels_as_one_silent_developer_item() -> None:
- """Context delta, current-turn block and language pin ride ONE append.
-
- Every separate developer item was one more thing the model audibly
- acknowledged — a live call spliced "Alles klar…" into the middle of its
- own answer (2026-08-05 19:13). The payload also has to SAY the update is
- silent configuration, or the model treats it as conversation.
- """
- client = _Client()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(instructions="Persona line.\nClock: 12:00.")
- )
- baseline = len(client.text_appends)
-
- await session.update_session(
- instructions="Persona line.\nClock: 12:01.",
- language="de",
- turn_directive="Directive A.",
- )
-
- assert len(client.text_appends) == baseline + 1
- _thread, payload, role = client.text_appends[-1]
- assert role == "developer"
- assert "Clock: 12:01." in payload
- assert "Directive A." in payload
- assert codex_subscription_mod._language_pin_text("de") in payload
- assert "silently" in payload.lower()
- await session.close()
-
-
-async def test_turn_directive_supersedes_instead_of_accumulating() -> None:
- """A changed turn directive is delivered WHOLE, with replace semantics.
-
- The three per-turn directives are mutually exclusive; a line-diff plus a
- blanket "everything stays in force" left the thread claiming "answer
- directly", "do not answer" and "say you are still working" all at once
- (independent review 2026-08-05).
- """
- client = _Client()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(instructions="Persona line.\nDirective A.")
- )
-
- await session.update_session(
- instructions="Persona line.\nDirective B.",
- turn_directive="Directive B.",
- )
- await session.update_session(
- instructions="Persona line.\nDirective A.",
- turn_directive="Directive A.",
- )
-
- appends = [text for _thread, text, _role in client.text_appends]
- # Turn 2: the directive travels ONLY in its superseding section, never
- # additionally as a diffed context line.
- assert "REPLACE every earlier instruction" in appends[0]
- assert "Directive B." in appends[0]
- assert appends[0].count("Directive B.") == 1
- # Turn 3: reverting re-issues the directive as a full replacement even
- # though an identical copy already sits in the thread's opening block.
- assert "REPLACE every earlier instruction" in appends[1]
- assert "Directive A." in appends[1]
- assert "Directive B." not in appends[1]
- await session.close()
-
-
-async def test_open_pins_language_only_for_an_explicit_reply_language() -> None:
- """brain.reply_language = de must pin the FIRST reply, auto must not."""
- client = _Client()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(
- transport_offer_sdp="v=0\r\no=offer",
- language="de",
- language_is_pinned=True,
- )
- )
-
- assert client.text_appends == []
- _thread_id, start = client.realtime_starts[0]
- assert codex_subscription_mod._language_pin_text("de") in start["trusted_prompt"]
- await session.close()
-
-
-async def test_same_language_is_reasserted_at_every_local_turn_boundary() -> None:
- """Auto-response can start before a large persona refresh takes effect.
-
- The concise language directive must therefore be the final developer item
- on every grounded turn, even when the resolved language did not change.
- """
- client = _Client()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(
- language="de",
- language_is_pinned=True,
- transport_offer_sdp="v=0\r\no=offer",
- )
- )
-
- await session.update_session(language="de")
-
- pin = codex_subscription_mod._language_pin_text("de")
- assert client.text_appends == [("thread-1", pin, "developer")]
- await session.close()
-
-
-async def test_open_relies_on_authoritative_app_server_auth_without_pre_probe() -> None:
- client = _UnauthenticatedClient()
- provider = _provider(client)
-
- with pytest.raises(RuntimeError, match="unauthenticated account"):
- await provider.open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))
-
- assert client.capability_calls == 0
- assert len(client.thread_starts) == 1
- assert client.realtime_starts == []
-
-
-async def test_orchestrator_capability_check_does_not_repeat_cli_auth_probe(
- monkeypatch,
-) -> None:
- provider = _provider(_Client())
-
- def _unexpected_probe(_cls):
- raise AssertionError("factory login probe must not repeat during handshake")
-
- monkeypatch.setattr(
- CodexSubscriptionRealtimeProvider,
- "external_login_ready",
- classmethod(_unexpected_probe),
- )
-
- assert await provider.can_open_duplex_session() is True
-
-
-def test_external_login_ready_respects_the_activation_block(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A permanently refused account must not be advertised as available."""
- from jarvis import codex_app_server
-
- monkeypatch.setattr(
- codex_app_server,
- "codex_subscription_activation_block",
- lambda: "Subscription voice permits only personal ChatGPT accounts.",
- )
- monkeypatch.setattr(
- codex_app_server,
- "codex_subscription_auth_snapshot",
- lambda _binary: pytest.fail("a blocked account needs no CLI probe"),
- )
-
- assert CodexSubscriptionRealtimeProvider.external_login_ready(None) is False
-
-
-async def test_verify_activation_keeps_successful_cold_transport_warm(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Provider selection warms the transport the first call will reuse."""
- from jarvis import codex_app_server
-
- events: list[str] = []
-
- class _Client:
- async def require_chatgpt_login(self) -> None:
- events.append("verified")
-
- async def close(self) -> None:
- events.append("closed")
-
- monkeypatch.setattr(
- codex_app_server,
- "get_shared_codex_app_server",
- lambda _binary: _Client(),
- )
-
- await CodexSubscriptionRealtimeProvider.verify_activation(SimpleNamespace())
-
- assert events == ["verified"]
-
-
-async def test_verify_activation_cleans_up_a_failed_cold_transport(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis import codex_app_server
-
- events: list[str] = []
-
- class _Client:
- async def require_chatgpt_login(self) -> None:
- events.append("failed")
- raise RuntimeError("login failed")
-
- async def close(self) -> None:
- events.append("closed")
-
- monkeypatch.setattr(
- codex_app_server,
- "get_shared_codex_app_server",
- lambda _binary: _Client(),
- )
-
- with pytest.raises(RuntimeError, match="login failed"):
- await CodexSubscriptionRealtimeProvider.verify_activation(SimpleNamespace())
-
- assert events == ["failed", "closed"]
-
-
-async def test_verify_activation_never_closes_a_client_carrying_a_call(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A client that was ALREADY ready is carrying a live session — verifying
- is harmless, closing it would cut the call mid-sentence."""
- from jarvis import codex_app_server
-
- events: list[str] = []
-
- class _Client:
- ready = True
-
- async def require_chatgpt_login(self) -> None:
- events.append("verified")
-
- async def close(self) -> None:
- events.append("closed")
-
- monkeypatch.setattr(
- codex_app_server,
- "get_shared_codex_app_server",
- lambda _binary: _Client(),
- )
-
- await CodexSubscriptionRealtimeProvider.verify_activation(SimpleNamespace())
-
- assert events == ["verified"]
-
-
- ("reason_code", "available", "authenticated", "expected"),
- [
- ("ready", True, True, True),
- ("login_required", False, False, False),
- # Transiently unknown must fail OPEN: voice-mode availability flips
- # (with a user-facing 400) on a fail-closed answer, while opening a
- # session performs the authoritative live account verification anyway.
- ("busy", False, False, True),
- ],
-)
-def test_external_login_ready_fails_open_on_transient_busy(
- monkeypatch: pytest.MonkeyPatch,
- reason_code: str,
- available: bool,
- authenticated: bool,
- expected: bool,
-) -> None:
- from jarvis import codex_app_server
-
- monkeypatch.setattr(
- codex_app_server,
- "codex_subscription_auth_snapshot",
- lambda _binary: SimpleNamespace(
- available=available,
- chatgpt_authenticated=authenticated,
- reason_code=reason_code,
- ),
- )
-
- assert CodexSubscriptionRealtimeProvider.external_login_ready(None) is expected
-
-
-async def test_send_audio_rides_the_media_track_not_a_sideband_append() -> None:
- """ChatGPT-Live has NO audio client event: the sideband append the retired
- v1 protocol used is rejected outright, so microphone PCM must reach the
- WebRTC media path instead."""
- client = _Client()
- provider = _provider(client)
- session = await provider.open_session(RealtimeSessionConfig())
-
- await session.send_audio(
- SimpleNamespace(pcm=b"\x01\x00\x02\x00", sample_rate=24_000, channels=1)
- )
-
- assert provider.test_endpoint.sent == [(b"\x01\x00\x02\x00", 24_000)]
- assert client.audio_appends == []
- await session.close()
- assert provider.test_endpoint.closed is True
-
-
-async def test_notifications_normalize_audio_transcripts_and_boundaries() -> None:
- client = _Client(
- [
- _Notification(
- "thread/realtime/itemAdded",
- {
- "threadId": "thread-1",
- "item": {
- "type": "input_audio_buffer.speech_started",
- "item_id": "input-1",
- },
- },
- ),
- _Notification(
- "thread/realtime/transcript/delta",
- {"threadId": "thread-1", "role": "user", "delta": "hello"},
- ),
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "user", "text": "hello"},
- ),
- _Notification(
- "thread/realtime/transcript/delta",
- {"threadId": "thread-1", "role": "assistant", "delta": "hi"},
- ),
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "hi"},
- ),
- ]
- )
- # This normalization test deliberately omits the optional local recognizer;
- # local-grounding behavior has dedicated tests below.
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- events = [event async for event in session.receive()]
-
- # No audio_delta here on purpose: ChatGPT-Live carries assistant audio on
- # the WebRTC media track, never as a sideband notification.
- assert [event.type for event in events] == [
- "speech_started",
- "input_transcript",
- "input_transcript",
- "output_transcript_delta",
- "turn_complete",
- "error",
- ]
- # Without a local recognizer the server transcript owns the final text.
- assert events[2].is_final is True
- assert events[2].item_id == "input-1"
- assert events[3].text == "hi"
- # A cleanly exhausted fake stream is still an unexpected transport death.
- assert "ended unexpectedly" in str(events[-1].error)
- await session.close()
-
-
-async def test_media_track_audio_becomes_normalized_audio_deltas() -> None:
- """Assistant audio arrives as RTP on ChatGPT-Live; it must reach the
- pipeline as ordinary audio_delta events so playback, the Orb, and the
- transcript-gated release keep working exactly as before."""
- client = _Client()
- # The notification stream stays open past the audio, exactly as it does
- # during a live call — otherwise the fake transport death would race the
- # media pump.
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.05,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "hi"},
- ),
- )
- ]
- )
- endpoint = _FakeAudioEndpoint(output_chunks=(b"\x01\x00\x02\x00", b"\x03\x00"))
- session = await _provider(client, endpoint=endpoint).open_session(RealtimeSessionConfig())
-
- audio = [event async for event in session.receive() if event.type == "audio_delta"]
-
- assert [event.audio.pcm for event in audio] == [b"\x01\x00\x02\x00", b"\x03\x00"]
- assert {event.audio.sample_rate for event in audio} == {24_000}
- assert {event.audio.channels for event in audio} == {1}
- await session.close()
-
-
-async def test_media_track_forwards_provider_silence_verbatim() -> None:
- """The reply's own pauses must survive the trip to the speaker.
-
- They used to be compressed away, which was right for the retired sideband
- protocol (audio arrived faster than realtime, so dropping silence really
- did shorten the wait). On a live WebRTC track it removes audio the player
- needed in order to keep playing: the output stream starves and the voice
- chops. Measured on 2026-08-02: six cuts inside a single answer.
- """
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.05,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "hi"},
- ),
- )
- ]
- )
- speech = (1000).to_bytes(2, "little", signed=True) * 480
- long_silence = b"\x00\x00" * (24_000 * 2)
- endpoint = _FakeAudioEndpoint(output_chunks=(speech, long_silence, speech))
- session = await _provider(client, endpoint=endpoint).open_session(RealtimeSessionConfig())
-
- audio = [event.audio.pcm async for event in session.receive() if event.type == "audio_delta"]
-
- assert b"".join(audio) == speech + long_silence + speech
- await session.close()
-
-
-async def test_default_done_waits_for_all_late_audio_before_one_completion(
- monkeypatch,
-) -> None:
- # The last chunk must land WELL inside the quiescence window: Windows
- # timer granularity (~15.6 ms) makes two sequential sleeps overshoot a
- # same-length single sleep, so a schedule that races the deadline exactly
- # loses deterministically there while passing elsewhere.
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.25)
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "hi"},
- ),
- ),
- # Keeps the notification stream open while the late media audio
- # arrives, as a live transport does.
- (0.6, _Notification("thread/realtime/keepalive", {"threadId": "thread-1"})),
- ]
- )
- # Late RTP audio must arrive inside the quiescence window so one turn ends
- # exactly once, after the last chunk.
- endpoint = _FakeAudioEndpoint(output_schedule=((0.05, b"\x01\x00"), (0.05, b"\x01\x00")))
- session = await _provider(client, endpoint=endpoint).open_session(RealtimeSessionConfig())
-
- events = [event async for event in session.receive()]
- event_types = [event.type for event in events]
-
- assert event_types.count("audio_delta") == 2
- assert event_types.count("turn_complete") == 1
- assert max(
- index for index, event_type in enumerate(event_types) if event_type == "audio_delta"
- ) < event_types.index("turn_complete")
- await session.close()
-
-
-async def test_later_assistant_delta_cancels_pending_completion_until_next_done(
- monkeypatch,
-) -> None:
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.02)
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "part"},
- ),
- ),
- (
- 0.01,
- _Notification(
- "thread/realtime/transcript/delta",
- {"threadId": "thread-1", "role": "assistant", "delta": "more"},
- ),
- ),
- ]
- )
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- events = [event async for event in session.receive()]
-
- assert not [event for event in events if event.type == "turn_complete"]
- await session.close()
-
-
- ("method", "params"),
- [
- (
- "thread/realtime/itemAdded",
- {"item": {"type": "input_audio_buffer.speech_started"}},
- ),
- (
- "thread/realtime/itemAdded",
- {"item": {"type": "response.cancelled"}},
- ),
- ("thread/realtime/error", {"message": "transport failed"}),
- ("thread/realtime/closed", {"reason": "closed"}),
- ],
-)
-async def test_terminal_or_interruption_event_cancels_pending_completion(
- monkeypatch,
- method: str,
- params: dict,
-) -> None:
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.01)
- done = _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "partial"},
- )
- cancelling = _Notification(method, {"threadId": "thread-1", **params})
- client = _Client([done, cancelling])
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- events = [event async for event in session.receive()]
-
- assert not [event for event in events if event.type == "turn_complete"]
- await session.close()
-
-
-async def test_duplicate_transcript_done_emits_one_completion(monkeypatch) -> None:
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.01)
- done = _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "done"},
- )
- client = _Client([done, done])
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- events = [event async for event in session.receive()]
-
- assert len([event for event in events if event.type == "turn_complete"]) == 1
- await session.close()
-
-
-async def test_handoff_without_transcript_preserves_neutral_boundary() -> None:
- client = _Client(
- [
- _Notification(
- "thread/realtime/itemAdded",
- {
- "threadId": "thread-1",
- "item": {"type": "handoff_request", "handoff_id": "handoff-1"},
- },
- )
- ]
- )
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- events = [event async for event in session.receive()]
-
- assert not [event for event in events if event.type == "turn_complete"]
- handoff = next(event for event in events if event.type == "handoff_requested")
- assert handoff.handoff_id == "handoff-1"
- assert handoff.text is None
- await session.close()
-
-
-async def test_handoff_preserves_item_transcript_and_interrupts_late_codex_turn() -> None:
- client = _Client(
- [
- _Notification(
- "thread/realtime/itemAdded",
- {
- "threadId": "thread-1",
- "item": {
- "type": "handoff_request",
- "handoff_id": "handoff-1",
- "input_transcript": "Please check the calendar",
- "active_transcript": [{"role": "user", "text": "older question"}],
- },
- },
- ),
- _Notification(
- "turn/started",
- {
- "threadId": "thread-1",
- "turn": {"id": "codex-turn-1"},
- },
- ),
- ]
- )
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- events = [event async for event in session.receive()]
-
- handoff = next(event for event in events if event.type == "handoff_requested")
- assert handoff.text == "Please check the calendar"
- assert handoff.handoff_id == "handoff-1"
- assert client.interrupts == [("thread-1", "codex-turn-1")]
- await session.close()
-
-
-async def test_done_then_handoff_cancels_synthetic_completion(monkeypatch) -> None:
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.01)
- client = _Client(
- [
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "partial"},
- ),
- _Notification(
- "thread/realtime/itemAdded",
- {
- "threadId": "thread-1",
- "item": {"type": "handoff_request", "handoff_id": "handoff-1"},
- },
- ),
- ]
- )
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- events = [event async for event in session.receive()]
-
- assert not [event for event in events if event.type == "turn_complete"]
- assert any(event.type == "handoff_requested" for event in events)
- await session.close()
-
-
-async def test_a_terminal_response_item_ends_the_turn_at_once(monkeypatch) -> None:
- """The server says when a response is over; Jarvis must not guess.
-
- The quiescence backstop is pushed out of reach here, so a completion can
- only come from the terminal item itself.
- """
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 10.0)
- client = _Client(
- [
- _Notification(
- "thread/realtime/started",
- {"threadId": "thread-1", "version": 3},
- ),
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "done"},
- ),
- _Notification(
- "thread/realtime/itemAdded",
- {"threadId": "thread-1", "item": {"type": "response.done"}},
- ),
- ]
- )
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- async with asyncio.timeout(0.2):
- events = [event async for event in session.receive()]
-
- assert len([event for event in events if event.type == "turn_complete"]) == 1
- assert session.realtime_version == "3"
- await session.close()
-
-
-async def test_transcript_done_is_a_part_boundary_not_a_turn(monkeypatch) -> None:
- """One answer, one ending.
-
- ChatGPT-Live streams a reply as several transcript parts. Treating each
- part's ``done`` as the end of the turn drained playback, armed a ~0.9 s
- echo window and re-armed the scrub gate three times inside ONE answer
- (measured live 2026-08-02) — the chopped voice, plus a microphone that went
- deaf between the pieces.
- """
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 10.0)
- parts = [
- _Notification(
- "thread/realtime/started",
- {"threadId": "thread-1", "version": 3},
- )
- ]
- for text in ("first. ", "second. ", "third."):
- parts.append(
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": text},
- )
- )
- parts.append(
- _Notification(
- "thread/realtime/itemAdded",
- {"threadId": "thread-1", "item": {"type": "response.done"}},
- )
- )
- session = await _provider(_Client(parts)).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- async with asyncio.timeout(0.2):
- events = [event async for event in session.receive()]
-
- assert len([event for event in events if event.type == "turn_complete"]) == 1
- # Every part still reaches the transcript consumers.
- assert [event.text for event in events if event.type == "output_transcript_delta"] == [
- "first. ",
- "second. ",
- "third.",
- ]
- await session.close()
-
-
-async def test_normalization_queue_backpressures_and_pump_cleans_up() -> None:
- client = _Client()
- subscription = _CountingSubscription()
- client.subscription = subscription
- # No local recognizer: this test isolates queue backpressure from transcript
- # grounding, which is covered independently below.
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
- stream = session.receive()
-
- first = await anext(stream)
- assert first.type == "input_transcript"
- await asyncio.sleep(0.01)
-
- assert subscription.yielded <= codex_subscription_mod._NORMALIZATION_QUEUE_MAX + 2
- yielded_before_close = subscription.yielded
- await stream.aclose()
- await asyncio.sleep(0)
- assert subscription.yielded == yielded_before_close
- await session.close()
-
-
-async def test_handoff_request_never_becomes_a_direct_tool_call() -> None:
- client = _Client(
- [
- _Notification(
- "thread/realtime/itemAdded",
- {
- "threadId": "thread-1",
- "item": {
- "type": "handoff_request",
- "handoff_id": "handoff-1",
- },
- },
- ),
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "Working"},
- ),
- ]
- )
- session = await _provider(client).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- events = [event async for event in session.receive()]
-
- assert not [event for event in events if event.type == "tool_call"]
- await session.close()
-
-
-async def test_provider_error_and_app_server_death_are_normalized() -> None:
- provider_error_client = _Client(
- [
- _Notification(
- "thread/realtime/error",
- {"threadId": "thread-1", "message": "experimental transport failed"},
- )
- ]
- )
- provider_session = await _provider(provider_error_client).open_session(RealtimeSessionConfig())
- provider_events = [event async for event in provider_session.receive()]
- assert provider_events[0].type == "error"
- assert provider_events[0].recoverable is False
-
- dead_client = _Client(failure=RuntimeError("process exited"))
- dead_session = await _provider(dead_client).open_session(RealtimeSessionConfig())
- dead_events = [event async for event in dead_session.receive()]
- assert dead_events[0].type == "error"
- assert dead_events[0].recoverable is True
- assert "notification stream failed" in str(dead_events[0].error)
- await provider_session.close()
- await dead_session.close()
-
-
-async def test_media_endpoint_failure_cleans_parallel_thread_before_realtime() -> None:
- """A failed local offer must not leave the parallel thread start behind."""
- client = _Client()
-
- class _BrokenEndpoint(_FakeAudioEndpoint):
- async def create_offer(self) -> str:
- raise RuntimeError("no local WebRTC endpoint")
-
- provider = _provider(client, endpoint=_BrokenEndpoint())
-
- with pytest.raises(RuntimeError, match="no local WebRTC endpoint"):
- await provider.open_session(RealtimeSessionConfig())
-
- assert len(client.thread_starts) == 1
- assert client.realtime_starts == []
- assert client.stops == ["thread-1"]
- assert client.unsubscribes == ["thread-1"]
- assert provider.test_endpoint.closed is True
-
-
-async def test_offer_thread_and_transcriber_warm_overlap() -> None:
- """Independent cold-start work runs concurrently, without timing guesses."""
- offer_started = asyncio.Event()
- warm_started = asyncio.Event()
- release_parallel_work = asyncio.Event()
-
- class _GatedEndpoint(_FakeAudioEndpoint):
- async def create_offer(self) -> str:
- offer_started.set()
- await release_parallel_work.wait()
- return await super().create_offer()
-
- class _GatedTranscriber:
- async def warm(self) -> bool:
- warm_started.set()
- await release_parallel_work.wait()
- return True
-
- async def close(self) -> None:
- return None
-
- class _GatedClient(_Client):
- async def thread_start(self, **kwargs):
- await asyncio.gather(offer_started.wait(), warm_started.wait())
- release_parallel_work.set()
- return await super().thread_start(**kwargs)
-
- client = _GatedClient()
- provider = _provider(
- client,
- endpoint=_GatedEndpoint(),
- input_transcriber_factory=_GatedTranscriber,
- )
-
- session = await asyncio.wait_for(provider.open_session(RealtimeSessionConfig()), timeout=1.0)
-
- assert offer_started.is_set()
- assert warm_started.is_set()
- await session.close()
-
-
-async def test_broker_keeps_answered_lease_until_provider_release() -> None:
- broker = RealtimeTransportOfferBroker()
- registration = await broker.register("offer-1", "v=0\r\no=one")
- lease = await broker.acquire()
- assert lease is not None
-
- assert await lease.answer("v=0\r\no=answer") is True
- answer = await registration.wait()
- assert answer.type == "answer"
- assert answer.answer_sdp == "v=0\r\no=answer"
-
- await lease.release()
- released = await registration.wait()
- assert released.type == "release"
- assert await broker.pending_count() == 0
-
-
[email protected](autouse=True)
-def _isolated_stun_media_path_memory():
- """The STUN media-path memory is process-global; tests must not leak it."""
- from jarvis import codex_app_server
-
- with codex_app_server._stun_media_path_lock:
- codex_app_server._stun_media_path_memory.clear()
- yield
- with codex_app_server._stun_media_path_lock:
- codex_app_server._stun_media_path_memory.clear()
-
-
-async def test_unconnectable_host_path_retries_with_stun(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Host candidates cost no gathering time and connect on an ordinary
- network; a network that needs a reflexive candidate must still work, so a
- dead media path is retried once WITH a STUN server."""
- from jarvis.realtime import webrtc_transport
-
- monkeypatch.setattr(webrtc_transport, "stun_ice_servers", lambda: ["stun"])
- WebRtcMediaPathUnavailable = webrtc_transport.WebRtcMediaPathUnavailable
-
- client = _Client()
- ice_configs: list[object] = []
-
- class _HostOnlyFails(_FakeAudioEndpoint):
- def __init__(self, ice_servers) -> None:
- super().__init__()
- self.ice_servers = ice_servers
-
- async def wait_connected(self, timeout_s: float = 15.0) -> None:
- del timeout_s
- if not self.ice_servers:
- raise WebRtcMediaPathUnavailable("media path failed")
- self.connected = True
-
- def factory(ice_servers=None) -> _HostOnlyFails:
- ice_configs.append(ice_servers)
- return _HostOnlyFails(ice_servers)
-
- provider = CodexSubscriptionRealtimeProvider(client=client, audio_endpoint_factory=factory)
-
- session = await provider.open_session(RealtimeSessionConfig())
-
- # First attempt host-only (no servers), second with STUN.
- assert ice_configs[0] is None
- assert ice_configs[1]
- assert len(ice_configs) == 2
- await session.close()
-
-
-async def test_stun_memory_starts_with_stun_and_host_success_clears_it(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A network that needed STUN last time skips the doomed host-only attempt;
- a later successful host-only connect forgets the preference again."""
- from jarvis import codex_app_server
- from jarvis.realtime import webrtc_transport
-
- monkeypatch.setattr(webrtc_transport, "stun_ice_servers", lambda: ["stun"])
-
- client = _Client()
- ice_configs: list[object] = []
-
- def factory(ice_servers=None) -> _FakeAudioEndpoint:
- ice_configs.append(ice_servers)
- return _FakeAudioEndpoint()
-
- provider = CodexSubscriptionRealtimeProvider(client=client, audio_endpoint_factory=factory)
-
- codex_app_server.record_media_path_outcome("chatgpt-live", needed_stun=True)
- session = await provider.open_session(RealtimeSessionConfig())
- await session.close()
- # STUN went FIRST and succeeded in a single attempt.
- assert ice_configs == [["stun"]]
- # The successful STUN connect keeps the preference armed.
- assert codex_app_server.media_path_prefers_stun("chatgpt-live")
-
- codex_app_server.record_media_path_outcome("chatgpt-live", needed_stun=False)
- ice_configs.clear()
- session = await provider.open_session(RealtimeSessionConfig())
- await session.close()
- # Forgotten preference restores host-candidates-first.
- assert ice_configs == [None]
- assert not codex_app_server.media_path_prefers_stun("chatgpt-live")
-
-
-async def test_each_session_negotiates_its_own_media_endpoint() -> None:
- """Every call owns a fresh peer: the answer is applied to it and the media
- path is proven live before the session is handed to the pipeline."""
- client = _Client()
- endpoints: list[_FakeAudioEndpoint] = []
-
- def factory(_ice_servers=None) -> _FakeAudioEndpoint:
- endpoint = _FakeAudioEndpoint()
- endpoints.append(endpoint)
- return endpoint
-
- provider = CodexSubscriptionRealtimeProvider(client=client, audio_endpoint_factory=factory)
-
- for _ in (1, 2):
- session = await provider.open_session(RealtimeSessionConfig())
- await session.close()
-
- assert len(endpoints) == 2
- assert all(endpoint.answers == ["v=0\r\nanswer"] for endpoint in endpoints)
- assert all(endpoint.connected for endpoint in endpoints)
- assert all(endpoint.closed for endpoint in endpoints)
- # The offer the provider sent is the one its OWN peer produced.
- assert [kwargs["offer_sdp"] for _thread, kwargs in client.realtime_starts] == [
- "v=0\r\no=python-peer\r\n",
- "v=0\r\no=python-peer\r\n",
- ]
-
-
-async def test_ui_disconnect_after_answer_removes_answered_lease() -> None:
- broker = RealtimeTransportOfferBroker()
- registration = await broker.register("offer-1", "v=0\r\no=one")
- lease = await broker.acquire()
- assert lease is not None
- assert await lease.answer("v=0\r\no=answer") is True
- assert (await registration.wait()).type == "answer"
-
- await registration.cancel()
-
- assert (await registration.wait()).type == "release"
- assert await broker.pending_count() == 0
- assert await lease.answer("v=0\r\no=late-answer") is False
-
-
-class _StubEndpointer:
- """Stands in for the local endpointer's word-agnostic energy verdict."""
-
- def __init__(self, speaking: bool) -> None:
- self._speaking = speaking
-
- def speech_recently(self, grace_ms: int = 2000) -> bool: # noqa: ARG002
- return self._speaking
-
- def feed(self, pcm, sample_rate) -> None: # noqa: ANN001, ARG002 - protocol
- return None
-
- async def next_event(self): # noqa: ANN202 - delivers nothing in these tests
- await asyncio.sleep(3600)
-
- async def close(self) -> None:
- return None
-
-
-class _RecoveringEndpointer(_StubEndpointer):
- def __init__(self, text: str, *, ground_call: bool = True) -> None:
- super().__init__(speaking=True)
- self.text = text
- self.recovery_calls: list[tuple[bytes, int]] = []
- self._events = asyncio.Queue()
- self._events.put_nowait(InputTranscriptEvent(kind="speech_started"))
- if ground_call:
- # Under the no-unsolicited-opening policy an answer only plays
- # once a user final exists.
- self._events.put_nowait(
- InputTranscriptEvent(kind="transcript", text="Hi.", is_final=True)
- )
-
- async def next_event(self): # noqa: ANN202 - test protocol
- return await self._events.get()
-
- async def transcribe_audio(self, pcm: bytes, *, sample_rate: int) -> str:
- self.recovery_calls.append((pcm, sample_rate))
- return self.text
-
-
-class _ScriptedInputTranscriber(_StubEndpointer):
- def __init__(self, events) -> None:
- super().__init__(speaking=True)
- self._events = asyncio.Queue()
- for event in events:
- self._events.put_nowait(event)
-
- async def next_event(self): # noqa: ANN202 - test protocol
- return await self._events.get()
-
-
-class _GroundedThenQuietTranscriber(_ScriptedInputTranscriber):
- """Delivers one real local utterance, then reports a quiet microphone."""
-
- def __init__(self) -> None:
- super().__init__(
- [
- InputTranscriptEvent(kind="speech_started"),
- InputTranscriptEvent(kind="transcript", text="What is up?", is_final=True),
- ]
- )
- self._speaking = False
-
-
-def _hallucination_client() -> _Client:
- return _Client(
- [
- _Notification(
- "thread/realtime/transcript/delta",
- {"threadId": "thread-1", "role": "user", "delta": "a_lee "},
- ),
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "user",
- "text": "a_lee pixelated image",
- },
- ),
- ]
- )
-
-
-async def _user_transcripts(*, speaking: bool | None) -> list:
- if speaking is None:
- transcriber = None
- elif speaking:
- transcriber = _ScriptedInputTranscriber([InputTranscriptEvent(kind="speech_started")])
- else:
- transcriber = _StubEndpointer(speaking=False)
- session = await _provider(
- _hallucination_client(), input_transcriber_factory=lambda: transcriber
- ).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))
- events = [event async for event in session.receive()]
- await session.close()
- return [event for event in events if event.type == "input_transcript"]
-
-
-async def test_a_server_transcript_without_microphone_energy_never_becomes_a_turn():
- """The live defect: the user said "Hallo, was geht?" and Jarvis recorded
- "a_lee pixelated image" as their words, then answered it in earnest.
- ChatGPT-Live transcribes the user itself and, like every recognizer, writes
- caption-shaped text over silence and over the echo of its own voice. Only
- audio energy separates the two - a hallucination is spelled flawlessly
- (AP-27)."""
- assert await _user_transcripts(speaking=False) == []
-
-
-async def test_a_server_transcript_backed_by_speech_shows_up_live():
- """While the user really is speaking, the far end's transcript is the only
- live text there is - dropping it would leave the bar blank mid-sentence."""
- transcripts = await _user_transcripts(speaking=True)
-
- assert [event.text for event in transcripts] == [
- "a_lee ",
- "a_lee pixelated image",
- ]
- # The local recognizer - the user's own, with their dictionary and bias
- # prompt - owns the FINAL text, so these stay a live preview.
- assert not any(event.is_final for event in transcripts)
-
-
-async def test_without_a_local_recognizer_the_server_transcript_is_final():
- """A host with no usable recognizer still has to reach a routed turn, or
- the provider talks while every Jarvis integration sits idle."""
- finals = [event for event in await _user_transcripts(speaking=None) if event.is_final]
-
- assert [event.text for event in finals] == ["a_lee pixelated image"]
-
-
-async def test_orphan_response_without_a_fresh_local_utterance_is_interrupted():
- """ChatGPT-Live must not turn its own output into a second user turn.
-
- The live failure started a second response two milliseconds after the first
- turn completed, before any final user transcript existed. Its server-side
- user preview then drifted to ``"sorry, i"`` while the model continued a
- made-up conversation. A fresh local speech boundary is the authority for
- another automatic response; server VAD and captions are not.
- """
- transcriber = _ScriptedInputTranscriber(
- [
- InputTranscriptEvent(kind="speech_started"),
- InputTranscriptEvent(kind="transcript", text="Hello", is_final=True),
- ]
- )
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.02,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "Hi."},
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/itemAdded",
- {"threadId": "thread-1", "item": {"type": "response.done"}},
- ),
- ),
- (
- 0.0,
- _Notification(
- "turn/started",
- {"threadId": "thread-1", "turn": {"id": "orphan-turn"}},
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/itemAdded",
- {
- "threadId": "thread-1",
- "item": {"type": "response.created"},
- },
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/delta",
- {"threadId": "thread-1", "role": "user", "delta": "sorry, i"},
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "text": "An invented second answer.",
- },
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/itemAdded",
- {
- "threadId": "thread-1",
- "item": {"type": "response.cancelled"},
- },
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/itemAdded",
- {"threadId": "thread-1", "item": {"type": "response.done"}},
- ),
- ),
- ]
- )
- session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
- RealtimeSessionConfig()
- )
-
- events = [event async for event in session.receive()]
-
- assert [event.text for event in events if event.type == "output_transcript_delta"] == ["Hi."]
- assert [event.type for event in events].count("turn_complete") == 1
- assert not [event for event in events if event.type == "interrupted"]
- assert not [
- event for event in events if event.type == "input_transcript" and not event.is_final
- ]
- assert client.interrupts == [("thread-1", "orphan-turn")]
- await session.close()
-
-
-async def test_ungrounded_server_turn_aborts_an_open_response_without_a_boundary(
- monkeypatch,
-):
- """A missing response boundary must not merge a self-dialogue forever.
-
- Live Codex v3 evidence (2026-08-02) carried no terminal response item. The
- legitimate answer therefore stayed open while silence produced a new
- server-side user caption, and every automatic reply was accepted as more
- of the original response. A RUN of ungrounded final captions must close the
- local turn and force a clean transport rebuild - a single one must not,
- because a server that transcribes with its own latency is normal and
- tearing the transport down for it costs a full handshake every turn.
- """
- monkeypatch.setattr(codex_subscription_mod, "_UNGROUNDED_RESPONSE_GRACE_S", 0.0)
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.01,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "Hi."},
- ),
- ),
- (
- 0.01,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "user", "text": "Thanks."},
- ),
- ),
- # A single late caption is survivable and must NOT tear the
- # transport down (a server that transcribes slowly is normal).
- # A RUN of them is the self-dialogue loop.
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "user", "text": "Sure thing."},
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "user", "text": "Anything else?"},
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "text": "An invented second side of the conversation.",
- },
- ),
- ),
- ]
- )
- session = await _provider(
- client,
- input_transcriber_factory=_GroundedThenQuietTranscriber,
- ).open_session(RealtimeSessionConfig())
-
- events = [event async for event in session.receive()]
-
- assert [event.text for event in events if event.type == "output_transcript_delta"] == ["Hi."]
- assert [event.type for event in events].count("turn_complete") == 1
- errors = [event for event in events if event.type == "error"]
- assert len(errors) == 1
- assert errors[0].recoverable is True
- assert errors[0].reconnect_advised is True
- assert "locally grounded" in str(errors[0].error)
- await session.close()
-
-
-async def test_ungrounded_turn_warning_uses_the_resolved_session_language(
- monkeypatch,
-):
- """A recovery warning must not switch the turn back to English."""
- monkeypatch.setattr(codex_subscription_mod, "_UNGROUNDED_RESPONSE_GRACE_S", 0.0)
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.01,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "Hallo."},
- ),
- ),
- (
- 0.01,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "user", "text": "Danke."},
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "user", "text": "Alles klar."},
- ),
- ),
- # A run, not a single late caption: one is survivable, a run is the
- # self-dialogue loop that earns the rebuild warning.
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "user",
- "text": "Und weiter?", # i18n-allow
- },
- ),
- ),
- ]
- )
- session = await _provider(
- client,
- input_transcriber_factory=_GroundedThenQuietTranscriber,
- ).open_session(RealtimeSessionConfig(language="de"))
-
- events = [event async for event in session.receive()]
-
- errors = [event for event in events if event.type == "error"]
- assert [event.error for event in errors] == [
- codex_subscription_mod._UNGROUNDED_TURN_MESSAGES["de"]
- ]
- await session.close()
-
-
-async def test_trusted_direct_speech_is_allowed_without_a_new_user_utterance():
- """Action readbacks intentionally create output outside a microphone turn."""
- transcriber = _StubEndpointer(speaking=False)
- client = _Client(
- [
- _Notification(
- "thread/realtime/itemAdded",
- {"threadId": "thread-1", "item": {"type": "response.created"}},
- ),
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "text": "The action is complete.",
- },
- ),
- _Notification(
- "thread/realtime/itemAdded",
- {"threadId": "thread-1", "item": {"type": "response.done"}},
- ),
- ]
- )
- session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
- RealtimeSessionConfig()
- )
- await session.send_speech("The action is complete.")
-
- events = [event async for event in session.receive()]
-
- assert client.speech_appends == [("thread-1", "The action is complete.")]
- assert [event.text for event in events if event.type == "output_transcript_delta"] == [
- "The action is complete."
- ]
- assert [event.type for event in events].count("turn_complete") == 1
- await session.close()
-
-
-async def test_local_failure_before_server_done_promotes_the_late_preview():
- """Either ordering must still commit the spoken user turn."""
- transcriber = _ScriptedInputTranscriber(
- [
- InputTranscriptEvent(kind="speech_started"),
- InputTranscriptEvent(kind="transcript_failed"),
- ]
- )
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.02,
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "user",
- "text": "Hello, what is up?",
- },
- ),
- )
- ]
- )
- session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
- RealtimeSessionConfig()
- )
-
- events = [event async for event in session.receive()]
-
- finals = [event for event in events if event.type == "input_transcript" and event.is_final]
- assert [event.text for event in finals] == ["Hello, what is up?"]
- await session.close()
-
-
-async def test_missing_output_transcript_is_recovered_from_provider_audio(
- monkeypatch,
-) -> None:
- """Provider audio must not become a silent turn when its text is absent.
-
- Highest-impact live defect, 2026-08-02: a correctly recognized casual
- greeting moved LISTENING -> PROCESSING -> LISTENING while the complete
- answer was discarded as "output transcript missing". The user heard
- nothing and the product looked as though it only kept listening.
- """
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.03)
- speech = (900).to_bytes(2, "little", signed=True) * 480
- silence = b"\x00\x00" * 480
- endpoint = _FakeAudioEndpoint(output_schedule=((0.01, speech), (0.0, silence)))
- transcriber = _RecoveringEndpointer("Hi there, everything is fine.")
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.2,
- _Notification("thread/realtime/keepalive", {"threadId": "thread-1"}),
- )
- ]
- )
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- events = []
- async for event in session.receive():
- events.append(event)
- if event.type == "turn_complete":
- break
-
- transcript_index = next(
- index for index, event in enumerate(events) if event.type == "output_transcript_delta"
- )
- complete_index = next(
- index for index, event in enumerate(events) if event.type == "turn_complete"
- )
- assert events[transcript_index].text == "Hi there, everything is fine."
- assert transcript_index < complete_index
- assert transcriber.recovery_calls == [(speech + silence, 24_000)]
- await session.close()
-
-
-async def test_media_track_end_is_a_rebuildable_transport_error() -> None:
- endpoint = _FakeAudioEndpoint(output_schedule=((0.0, None),))
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.2,
- _Notification("thread/realtime/keepalive", {"threadId": "thread-1"}),
- )
- ]
- )
- session = await _provider(client, endpoint=endpoint).open_session(RealtimeSessionConfig())
-
- event = await anext(session.receive())
-
- assert event.type == "error"
- assert "media track ended unexpectedly" in str(event.error)
- assert event.recoverable is True
- assert session.rebuild_on_transport_death is True
- await session.close()
-
-
-def _keeps_stream_open(*extra):
- """Notifications plus a late one, so the stream outlives the assertions."""
- return _ScheduledSubscription(
- [
- (
- 0.0,
- _Notification(
- "thread/realtime/started",
- {"threadId": "thread-1", "version": 3},
- ),
- ),
- *extra,
- (
- 2.0,
- _Notification(
- "thread/realtime/started",
- {"threadId": "thread-1", "version": 3},
- ),
- ),
- ]
- )
-
-
-_ARMS_THE_BACKSTOP = (
- 0.0,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "hi"},
- ),
-)
-
-
-async def test_silent_frames_never_hold_a_turn_open(monkeypatch) -> None:
- """The trap that makes the backstop the ONLY safe boundary.
-
- The media track keeps sending silence between turns. If silence re-armed
- the quiescence timer, that timer could never fire — and since the terminal
- response item's v3 spelling is not yet confirmed live, a turn would hang
- forever on any protocol that omits it.
- """
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.1)
- client = _Client()
- client.subscription = _keeps_stream_open(_ARMS_THE_BACKSTOP)
- silence = b"\x00\x00" * 480
- endpoint = _FakeAudioEndpoint(output_schedule=tuple((0.02, silence) for _ in range(25)))
- session = await _provider(client, endpoint=endpoint).open_session(RealtimeSessionConfig())
-
- completions = 0
- async with asyncio.timeout(1.0):
- async for event in session.receive():
- if event.type == "turn_complete":
- completions += 1
- break
-
- assert completions == 1
- await session.close()
-
-
-async def test_audible_frames_keep_a_turn_open(monkeypatch) -> None:
- """The other half: real speech must not be cut off by the backstop.
-
- Paired with the test above on purpose — together they rule out an
- implementation that satisfies one by ignoring audio altogether.
- """
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.1)
- client = _Client()
- client.subscription = _keeps_stream_open(_ARMS_THE_BACKSTOP)
- speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(output_schedule=tuple((0.02, speech) for _ in range(25)))
- session = await _provider(client, endpoint=endpoint).open_session(RealtimeSessionConfig())
-
- events = []
- with contextlib.suppress(TimeoutError):
- async with asyncio.timeout(0.3):
- async for event in session.receive():
- events.append(event)
-
- assert [event for event in events if event.type == "audio_delta"]
- assert not [event for event in events if event.type == "turn_complete"]
- await session.close()
-
-
-async def test_an_unknown_realtime_item_type_is_named_once(caplog) -> None:
- """Silently swallowing unknown items is why neither the real terminal
- response item nor the never-observed handoff item could be identified from
- a whole call's log (AP-30). The name is logged; the payload never is."""
- caplog.set_level(logging.INFO)
- unknown = _Notification(
- "thread/realtime/itemAdded",
- {
- "threadId": "thread-1",
- "item": {"type": "response.output_audio.done", "secret": "transcript"},
- },
- )
- session = await _provider(_Client([unknown, unknown])).open_session(
- RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")
- )
-
- events = [event async for event in session.receive()]
-
- assert not [event for event in events if event.type == "turn_complete"]
- named = [
- record.getMessage()
- for record in caplog.records
- if "unhandled realtime item type" in record.getMessage()
- ]
- assert len(named) == 1
- assert "response.output_audio.done" in named[0]
- assert "transcript" not in named[0]
- await session.close()
-
-
-async def test_the_negotiated_protocol_and_voice_are_logged(caplog) -> None:
- """ "Is this really what Codex uses?" has to be answerable from evidence."""
- caplog.set_level(logging.INFO)
- client = _Client(
- [
- _Notification(
- "thread/realtime/started",
- {"threadId": "thread-1", "version": 3},
- )
- ]
- )
- session = await _provider(client).open_session(RealtimeSessionConfig(voice="cove"))
-
- [event async for event in session.receive()]
-
- assert any(
- "negotiated protocol 3" in record.getMessage() and "cove" in record.getMessage()
- for record in caplog.records
- )
- await session.close()
-
-
-async def test_warm_transport_never_raises(monkeypatch) -> None:
- """The whole point is to move a cold start OUT of the call. A warm that
- fails may only mean the next call pays what it pays today."""
- calls = []
-
- async def _boom(cfg): # noqa: ANN001 - classmethod shape
- calls.append(cfg)
- raise RuntimeError("no login")
-
- monkeypatch.setattr(CodexSubscriptionRealtimeProvider, "verify_activation", _boom)
-
- await CodexSubscriptionRealtimeProvider.warm_transport(object())
-
- assert len(calls) == 1
-
-
-async def test_a_reply_without_any_transcript_still_ends_its_turn(monkeypatch) -> None:
- """A turn that never ends leaves Jarvis DEAF for the rest of the call.
-
- Half-duplex keeps the microphone shut while the assistant is speaking, so
- a missing boundary is not a cosmetic problem — the user talks and nothing
- reaches the session. The backstop therefore has to be ARMED by audible
- audio itself, not only by a transcript part that may never arrive.
- """
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.1)
- client = _Client()
- client.subscription = _keeps_stream_open() # no transcript notification at all
- speech = (1000).to_bytes(2, "little", signed=True) * 480
- silence = b"\x00\x00" * 480
- endpoint = _FakeAudioEndpoint(
- output_schedule=(
- *((0.02, speech) for _ in range(10)),
- *((0.02, silence) for _ in range(25)),
- )
- )
- session = await _provider(client, endpoint=endpoint).open_session(RealtimeSessionConfig())
-
- completions = 0
- async with asyncio.timeout(1.5):
- async for event in session.receive():
- if event.type == "turn_complete":
- completions += 1
- break
-
- assert completions == 1
- await session.close()
-
-
-class _ScheduledInputTranscriber(_StubEndpointer):
- """Local endpointer whose events arrive at controlled times.
-
- ``_ScriptedInputTranscriber`` delivers everything at once, which cannot
- express "the user speaks AFTER the far end already said something" — the
- exact ordering the grounding gate has to survive.
- """
-
- def __init__(self, scheduled_events, *, speaking: bool = True) -> None:
- super().__init__(speaking=speaking)
- self._scheduled = list(scheduled_events)
-
- async def next_event(self): # noqa: ANN202 - test protocol
- if not self._scheduled:
- await asyncio.sleep(3600)
- delay_s, event = self._scheduled.pop(0)
- if delay_s:
- await asyncio.sleep(delay_s)
- return event
-
-
-async def _collect_until(session, *, stop_after: int, kind: str, timeout_s: float):
- """Drain the session until ``stop_after`` events of ``kind`` were seen."""
- events = []
- seen = 0
- try:
- async with asyncio.timeout(timeout_s):
- async for event in session.receive():
- events.append(event)
- if event.type == kind:
- seen += 1
- if seen >= stop_after:
- break
- except TimeoutError:
- pass
- return events
-
-
-async def test_provider_speech_start_does_not_duplicate_local_boundary() -> None:
- """A late server VAD edge is the same utterance, not a new barge-in.
-
- ChatGPT-Live commonly sends it after the locally grounded final, while the
- answer is already opening. Forwarding both boundaries cancels that answer
- and strands the following response generation behind the interrupt barrier.
- """
- transcriber = _ScheduledInputTranscriber(
- [
- (0.01, InputTranscriptEvent(kind="speech_started")),
- (
- 0.0,
- InputTranscriptEvent(kind="transcript", text="Hello", is_final=True),
- ),
- ]
- )
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.04,
- _Notification(
- "thread/realtime/itemAdded",
- {
- "threadId": "thread-1",
- "item": {
- "type": "input_audio_buffer.speech_started",
- "item_id": "input-1",
- },
- },
- ),
- ),
- (
- 0.02,
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": "Hi there.",
- },
- ),
- ),
- ]
- )
- session = await _provider(
- client,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- events = await _collect_until(
- session,
- stop_after=1,
- kind="output_transcript_delta",
- timeout_s=1.0,
- )
-
- assert [event.type for event in events].count("speech_started") == 1
- assert [event.text for event in events if event.type == "output_transcript_delta"] == [
- "Hi there."
- ]
- assert session.diagnostics().get("duplicate_provider_speech_starts_suppressed", 0) == 1
- await session.close()
-
-
-async def test_own_cancel_ack_keeps_the_speech_turn_answerable() -> None:
- """A delayed cancel acknowledgement is not a second user barge-in.
-
- Live protocol v3 delivered ``response.cancelled`` after the local FINAL
- had already re-authorized the response. Treating that acknowledgement as
- an external interrupt both split the recorded turn and consumed the only
- entitlement for the answer, leaving a healthy session permanently mute.
- """
- transcriber = _ScheduledInputTranscriber(
- [
- (0.02, InputTranscriptEvent(kind="speech_started")),
- (0.0, InputTranscriptEvent(kind="transcript", text="Hello", is_final=True)),
- ]
- )
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": "Unsolicited opener.",
- },
- ),
- ),
- (
- 0.04,
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": "Answer head. ",
- },
- ),
- ),
- (
- 0.01,
- _Notification(
- "thread/realtime/itemAdded",
- {
- "threadId": "thread-1",
- "item": {"type": "response.cancelled"},
- },
- ),
- ),
- (
- 0.01,
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": "Answer tail.",
- },
- ),
- ),
- ]
- )
- session = await _provider(
- client,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- events = []
- async with asyncio.timeout(1.0):
- async for event in session.receive():
- events.append(event)
- if event.type == "speech_started":
- await session.interrupt()
- if event.type == "output_transcript_delta" and event.text == "Answer tail.":
- break
-
- assert [event.text for event in events if event.type == "output_transcript_delta"] == [
- "Answer head. ",
- "Answer tail.",
- ]
- cancelled = [event for event in events if event.type == "interrupted"]
- assert len(cancelled) == 1
- assert cancelled[0].self_initiated is True
- assert session.diagnostics().get("self_initiated_cancellations", 0) == 1
- await session.close()
-
-
-async def test_a_refused_response_does_not_deafen_the_next_real_turn() -> None:
- """AD-1: one refusal must not decide the rest of the call.
-
- The gate caches its verdict for the whole response it refused, and a
- ChatGPT-Live response has no reliable end marker. A single ungrounded
- response therefore used to keep ``response_open`` true forever: every
- later frame inherited that one "no", so the session stayed connected,
- kept listening, and never answered again. A locally energy-grounded
- utterance is the one signal the far end cannot fake, so it always
- reopens the gate.
- """
- transcriber = _ScheduledInputTranscriber(
- [
- (0.05, InputTranscriptEvent(kind="speech_started")),
- (0.0, InputTranscriptEvent(kind="transcript", text="Hello", is_final=True)),
- ]
- )
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- # Arrives before any local speech: correctly refused.
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "Echo."},
- ),
- ),
- # Arrives after the user really spoke: must be delivered.
- (
- 0.15,
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "text": "The real answer.",
- },
- ),
- ),
- ]
- )
- session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
- RealtimeSessionConfig()
- )
-
- events = [event async for event in session.receive()]
-
- assert [event.text for event in events if event.type == "output_transcript_delta"] == [
- "The real answer."
- ]
- await session.close()
-
-
-async def test_a_stale_refusal_is_reconsidered_and_still_refuses_a_self_echo(
- monkeypatch,
-) -> None:
- """Reopening the gate must not be a way in for the echo it refused.
-
- The refusal is reconsidered so it cannot latch, but reconsidering means
- re-deriving the verdict from scratch — with no fresh local utterance and
- no trusted injection the answer is still "no".
- """
- monkeypatch.setattr(codex_subscription_mod, "_REJECTED_RESPONSE_MAX_S", 0.0)
- client = _Client(
- [
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "One."},
- ),
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "Two."},
- ),
- ]
- )
- session = await _provider(
- client, input_transcriber_factory=lambda: _StubEndpointer(speaking=False)
- ).open_session(RealtimeSessionConfig())
-
- events = [event async for event in session.receive()]
-
- assert not [event for event in events if event.type == "output_transcript_delta"]
- await session.close()
-
-
-async def test_a_pause_inside_one_reply_does_not_cut_off_its_remainder(
- monkeypatch,
-) -> None:
- """AD-2: the local backstop must not retire the user's entitlement.
-
- The backstop closes the LOCAL turn on silence; it proves nothing about the
- provider's response. Spending the utterance there made the rest of the
- same answer look like a brand-new ungrounded response, which the gate then
- refused — one ordinary thinking pause and the reply was cut off mid-way.
- """
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.05)
- speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(
- # The gap is far longer than the backstop: a real in-reply pause.
- output_schedule=((0.02, speech), (0.30, speech))
- )
- transcriber = _ScheduledInputTranscriber(
- [
- (0.0, InputTranscriptEvent(kind="speech_started")),
- # Grounded call: the first answer needs a user final now.
- (
- 0.0,
- InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
- ),
- ]
- )
- client = _Client()
- client.subscription = _keeps_stream_open()
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- events = await _collect_until(session, stop_after=2, kind="audio_delta", timeout_s=1.5)
-
- assert [event.type for event in events].count("audio_delta") == 2
- # The backstop still delivered its boundary between the two halves.
- assert [event.type for event in events].count("turn_complete") == 1
- await session.close()
-
-
-async def test_a_completed_turn_still_refuses_the_next_ungrounded_response() -> None:
- """The self-dialogue guard, pinned against the continuation allowance.
-
- Letting the rest of ONE answer through must not let a SECOND answer
- through. Protocol proof that the response ended (here the terminal item)
- retires the entitlement immediately, so the invented follow-up is refused
- even though the far end is still producing output milliseconds later.
- """
- transcriber = _ScriptedInputTranscriber(
- [
- InputTranscriptEvent(kind="speech_started"),
- # Grounded call: the first answer needs a user final now.
- InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
- ]
- )
- client = _Client(
- [
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "Answer one."},
- ),
- _Notification(
- "thread/realtime/itemAdded",
- {"threadId": "thread-1", "item": {"type": "response.done"}},
- ),
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "text": "An invented second answer.",
- },
- ),
- ]
- )
- session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
- RealtimeSessionConfig()
- )
-
- events = [event async for event in session.receive()]
-
- assert [event.text for event in events if event.type == "output_transcript_delta"] == [
- "Answer one."
- ]
- assert [event.type for event in events].count("turn_complete") == 1
- await session.close()
-
-
-async def test_an_invented_user_caption_retires_the_entitlement() -> None:
- """The other half of the self-dialogue guard, without a terminal item.
-
- ChatGPT-Live announced no response boundary in the live evidence, so the
- marker that the model considers its turn over is the user caption it
- invents next. That caption ends the entitlement, and the answer it writes
- for its own invented turn is refused.
- """
- transcriber = _ScriptedInputTranscriber(
- [
- InputTranscriptEvent(kind="speech_started"),
- # Grounded call: the first answer needs a user final now.
- InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
- ]
- )
- transcriber._speaking = False # the microphone is quiet from here on
- client = _Client(
- [
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "Answer one."},
- ),
- _Notification(
- "thread/realtime/transcript/delta",
- {"threadId": "thread-1", "role": "user", "delta": "thanks, i"},
- ),
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "text": "An invented second answer.",
- },
- ),
- ]
- )
- session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
- RealtimeSessionConfig()
- )
-
- events = [event async for event in session.receive()]
-
- assert [event.text for event in events if event.type == "output_transcript_delta"] == [
- "Answer one."
- ]
- await session.close()
-
-
-async def test_interrupt_drops_the_remainder_without_any_codex_turn_id(
- monkeypatch,
-) -> None:
- """AD-3: barge-in must work on an ordinary ChatGPT-Live response.
-
- ``turn/interrupt`` addresses an app-server TURN and a realtime response
- never announces one, so the remote call had nothing to interrupt and the
- assistant simply kept talking into an already-open microphone. The local
- half is the one that always works.
- """
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 5.0)
- speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(output_schedule=((0.02, speech), (0.15, speech), (0.05, speech)))
- transcriber = _ScheduledInputTranscriber(
- [
- (0.0, InputTranscriptEvent(kind="speech_started")),
- # Grounded call: the first answer needs a user final now.
- (
- 0.0,
- InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
- ),
- ]
- )
- client = _Client()
- client.subscription = _keeps_stream_open()
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- stream = session.receive()
- async with asyncio.timeout(1.5):
- async for event in stream:
- if event.type == "audio_delta":
- break
-
- await session.interrupt()
-
- later_audio = []
- with contextlib.suppress(TimeoutError):
- async with asyncio.timeout(0.6):
- async for event in stream:
- if event.type == "audio_delta":
- later_audio.append(event)
-
- # No Codex turn was ever announced, so the remote interrupt had no target.
- assert client.interrupts == []
- assert later_audio == []
- await session.close()
-
-
-async def test_late_provider_transcript_is_shadow_recovered_for_the_gate(
- monkeypatch,
-) -> None:
- """Audible audio with no provider transcript earns a SHADOW delta.
-
- ChatGPT-Live's transcripts can lag their audio by seconds; the session's
- scrub gate holds all of it fail-closed until SOME transcript arrives
- (live 2026-08-05 20:42: the reply's first audio sat 7.4 s in the opening
- hold). The local recognizer recovers vetting text early; the shadow flag
- keeps it out of the user-visible transcript.
- """
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_AFTER_S", 0.05)
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_RETRY_S", 0.01)
- speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(
- output_schedule=(
- (0.02, speech),
- (0.05, speech),
- (0.05, speech),
- (0.05, speech),
- (0.05, speech),
- )
- )
- transcriber = _RecoveringEndpointer("Here is the answer.")
- # The user's utterance must CLOSE (final transcript) before the shadow
- # attempt may borrow the shared recognizer (review R2).
- transcriber._events.put_nowait(
- InputTranscriptEvent(kind="transcript", text="Hi", is_final=True)
- )
- client = _Client()
- client.subscription = _keeps_stream_open()
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- shadow = None
- with contextlib.suppress(TimeoutError):
- async with asyncio.timeout(1.5):
- async for event in session.receive():
- if event.type == "output_transcript_delta" and getattr(event, "shadow", False):
- shadow = event
- break
-
- assert shadow is not None
- assert shadow.text == "Here is the answer."
- assert transcriber.recovery_calls
- await session.close()
-
-
-async def test_slow_shadow_recovery_never_stalls_the_receive_pump(
- monkeypatch,
-) -> None:
- """A slow recognizer must not block audio delivery (review R1, measured).
-
- The first inline implementation held the whole receive loop for the
- recognizer's own time bound — audio stalled and the user's speech edge
- arrived seconds late. The recovery now runs as a background task.
- """
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_AFTER_S", 0.05)
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_RETRY_S", 0.01)
-
- class _SlowRecoveringEndpointer(_RecoveringEndpointer):
- async def transcribe_audio(self, pcm: bytes, *, sample_rate: int) -> str:
- await asyncio.sleep(0.4)
- return await super().transcribe_audio(pcm, sample_rate=sample_rate)
-
- speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(output_schedule=tuple((0.04, speech) for _ in range(14)))
- transcriber = _SlowRecoveringEndpointer("Here is the answer.")
- transcriber._events.put_nowait(
- InputTranscriptEvent(kind="transcript", text="Hi", is_final=True)
- )
- client = _Client()
- client.subscription = _keeps_stream_open()
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- audio_before_shadow = 0
- shadow_seen = False
- with contextlib.suppress(TimeoutError):
- async with asyncio.timeout(2.0):
- async for event in session.receive():
- if event.type == "audio_delta" and not shadow_seen:
- audio_before_shadow += 1
- if event.type == "output_transcript_delta" and getattr(event, "shadow", False):
- shadow_seen = True
- break
-
- assert shadow_seen
- # While the recognizer slept 0.4 s, ~10 further 40 ms chunks were due;
- # a blocking implementation delivers almost none of them before the
- # shadow event.
- assert audio_before_shadow >= 8
- await session.close()
-
-
-async def test_shadow_recovery_yields_to_an_open_user_utterance(
- monkeypatch,
-) -> None:
- """The microphone owns the shared recognizer mid-utterance (review R2)."""
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_AFTER_S", 0.05)
- monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_RETRY_S", 0.01)
- speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(output_schedule=tuple((0.04, speech) for _ in range(8)))
- # speech_started with no final: the utterance stays open for the whole
- # window, so no shadow attempt may run (and under the
- # no-unsolicited-opening policy the response never plays either).
- transcriber = _RecoveringEndpointer("Must never be used.", ground_call=False)
- client = _Client()
- client.subscription = _keeps_stream_open()
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- with contextlib.suppress(TimeoutError):
- async with asyncio.timeout(0.8):
- async for event in session.receive():
- assert not (
- event.type == "output_transcript_delta" and getattr(event, "shadow", False)
- )
-
- assert transcriber.recovery_calls == []
- await session.close()
-
-
-async def test_interrupt_retires_an_entitlement_the_response_never_used(
- monkeypatch,
-) -> None:
- """A delegation interrupt must beat the response's FIRST frame too.
-
- When Jarvis takes a turn deterministically it interrupts before the far
- end has begun streaming. Closing only the OPEN response left the spoken
- utterance's entitlement standing, so the "retired" native answer simply
- started a moment later and played over the trusted delegate reply (live
- 2026-08-04: an unrelated English fragment replaced the computed weather
- answer).
- """
- speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(output_schedule=((0.35, speech), (0.02, speech)))
- transcriber = _ScheduledInputTranscriber(
- [
- (0.0, InputTranscriptEvent(kind="speech_started")),
- (
- 0.02,
- InputTranscriptEvent(kind="transcript", text="Wetter morgen?", is_final=True),
- ),
- ]
- )
- client = _Client()
- client.subscription = _keeps_stream_open()
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- stream = session.receive()
- async with asyncio.timeout(1.5):
- async for event in stream:
- if event.type == "input_transcript" and event.is_final:
- break
-
- await session.interrupt(retire_input_entitlement=True)
-
- audio_after = []
- with contextlib.suppress(TimeoutError):
- async with asyncio.timeout(0.8):
- async for event in stream:
- if event.type == "audio_delta":
- audio_after.append(event)
-
- assert audio_after == []
- await session.close()
-
-
-async def test_barge_in_never_consumes_the_new_utterances_entitlement() -> None:
- """A plain barge-in interrupt must keep the NEW question answerable.
-
- At the moment ``_barge_in`` fires, the local input generation already
- belongs to the user's new utterance. Retiring it there consumed that
- question's one response entitlement, so the assistant fell permanently
- silent after every barge-in (independent review 2026-08-05: 3 frames
- before the change, 0 after). Only a delegation may retire the
- entitlement, via ``retire_input_entitlement=True``.
- """
- speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(output_schedule=((0.5, speech), (0.02, speech)))
- transcriber = _ScheduledInputTranscriber(
- [
- (0.0, InputTranscriptEvent(kind="speech_started")),
- (
- 0.02,
- InputTranscriptEvent(kind="transcript", text="Frage eins", is_final=True),
- ),
- (0.05, InputTranscriptEvent(kind="speech_started")),
- (
- 0.02,
- InputTranscriptEvent(kind="transcript", text="Warte, anders", is_final=True),
- ),
- ]
- )
- client = _Client()
- client.subscription = _keeps_stream_open()
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- stream = session.receive()
- finals = 0
- async with asyncio.timeout(1.5):
- async for event in stream:
- if event.type == "input_transcript" and event.is_final:
- finals += 1
- if finals == 2:
- break
-
- await session.interrupt()
-
- audio_after = []
- with contextlib.suppress(TimeoutError):
- async with asyncio.timeout(1.0):
- async for event in stream:
- if event.type == "audio_delta":
- audio_after.append(event)
- break
-
- assert audio_after, "the far end's answer to the barge-in utterance must stay audible"
- await session.close()
-
-
-async def test_post_interrupt_captions_do_not_feed_the_rebuild_counter(
- monkeypatch,
-) -> None:
- """Echo captions caused by OUR OWN cut must not tear the transport down.
-
- The far end predictably reacts to a local interrupt with captions of its
- own truncated speech. Counting those toward the self-dialogue rebuild
- threshold turned every delegation into a rebuild storm (live 2026-08-04:
- three transport rebuilds inside one 43 s call).
- """
- monkeypatch.setattr(codex_subscription_mod, "_UNGROUNDED_RESPONSE_GRACE_S", 0.0)
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.01,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "Hi."},
- ),
- ),
- (
- 0.02,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "user", "text": "Thanks."},
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "user", "text": "Sure thing."},
- ),
- ),
- (
- 0.0,
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "user", "text": "Anything else?"},
- ),
- ),
- ]
- )
- session = await _provider(
- client,
- input_transcriber_factory=_GroundedThenQuietTranscriber,
- ).open_session(RealtimeSessionConfig())
-
- stream = session.receive()
- async with asyncio.timeout(1.5):
- async for event in stream:
- if event.type == "output_transcript_delta":
- break
-
- await session.interrupt()
-
- events = []
- with contextlib.suppress(TimeoutError):
- async with asyncio.timeout(0.8):
- async for event in stream:
- events.append(event)
-
- rebuild_errors = [
- event
- for event in events
- if event.type == "error" and getattr(event, "reconnect_advised", False)
- ]
- assert rebuild_errors == []
- await session.close()
-
-
-def _self_echo_client(rounds: int) -> _Client:
- """A far end answering itself: each refused turn captions its own words.
-
- One ungrounded user caption closes the open response, the assistant text
- that follows opens a new one with nothing local behind it — a refusal —
- and the caption after that is the far end transcribing the very words we
- just cut. That is the shape of the live 17:41 loop.
- """
- events = [
- _Notification(
- "thread/realtime/transcript/delta",
- {"threadId": "thread-1", "role": "assistant", "delta": "Hi."},
- )
- ]
- for index in range(rounds):
- events.append(
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "user", "text": f"echo {index}"},
- )
- )
- events.append(
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": f"invented turn {index}",
- },
- )
- )
- return _Client(events)
-
-
-async def _drain(session) -> list:
- events = []
- with contextlib.suppress(TimeoutError):
- async with asyncio.timeout(2.0):
- async for event in session.receive():
- events.append(event)
- return events
-
-
-async def test_a_refusals_own_echo_captions_never_tear_the_transport_down(
- monkeypatch,
-) -> None:
- """BUG-124: refusing a turn is a LOCAL interrupt and must arm the grace.
-
- Live 2026-08-06 17:41: every refusal cut the far end, the far end
- captioned its own truncated words back as a user turn — the caption was
- the first words of the answer just cut — and two of those captions
- rebuilt the transport. Twice in six seconds, with the loop back each time.
- """
- monkeypatch.setattr(codex_subscription_mod, "_UNGROUNDED_RESPONSE_GRACE_S", 0.0)
- # High enough that only the caption counter could fire here: three rounds
- # deliver three ungrounded final captions against a threshold of two, so
- # this test fails outright unless the refusals arm the grace window.
- monkeypatch.setattr(codex_subscription_mod, "_REFUSALS_BEFORE_REBUILD", 99)
- session = await _provider(
- _self_echo_client(rounds=3),
- input_transcriber_factory=_GroundedThenQuietTranscriber,
- ).open_session(RealtimeSessionConfig())
-
- events = await _drain(session)
-
- assert [
- event
- for event in events
- if event.type == "error" and getattr(event, "reconnect_advised", False)
- ] == []
- await session.close()
-
-
-async def test_a_run_of_refusals_is_what_proves_the_self_dialogue_loop(
- monkeypatch,
-) -> None:
- """The honest signal: refusals, which our own reaction cannot manufacture.
-
- With the post-interrupt grace now covering refusals, the caption counter
- can no longer see a storm at all — so the storm needs its own detector, or
- a call would refuse every answer forever in silence (the 17:39 call died
- exactly that way, and only an app restart recovered it).
- """
- monkeypatch.setattr(codex_subscription_mod, "_UNGROUNDED_RESPONSE_GRACE_S", 0.0)
- monkeypatch.setattr(codex_subscription_mod, "_REFUSALS_BEFORE_REBUILD", 3)
- client = _self_echo_client(rounds=6)
- session = await _provider(
- client,
- input_transcriber_factory=_GroundedThenQuietTranscriber,
- ).open_session(RealtimeSessionConfig())
-
- events = await _drain(session)
-
- rebuild_errors = [
- event
- for event in events
- if event.type == "error" and getattr(event, "reconnect_advised", False)
- ]
- assert len(rebuild_errors) == 1
- assert rebuild_errors[0].recoverable is True
- assert events[-1].type == "turn_complete"
- # Only the FIRST refusal of the run interrupts: cutting a turn is what
- # makes ChatGPT-Live start the next one, so a storm is left to run out.
- assert len(client.interrupts) <= 1
- await session.close()
-
-
-async def test_truncate_reports_the_played_position_to_the_model() -> None:
- """AD-3: the model must learn how much of its answer was actually heard.
-
- ChatGPT-Live has no truncate client event, so the position travels as an
- inert developer note. Without it the model believes the whole answer was
- heard and grounds the next turn in words the user never got.
- """
- client = _Client()
- session = await _provider(client).open_session(RealtimeSessionConfig())
- # Opening the session pins the reply language, which is itself a developer
- # write; count from there so this test measures only what truncate adds.
- baseline = len(client.text_appends)
-
- # Nothing was interrupted yet: a stray truncate must not write anything.
- await session.truncate(audio_end_ms=900)
- assert len(client.text_appends) == baseline
-
- await session.interrupt()
- await session.truncate(audio_end_ms=900)
-
- assert len(client.text_appends) == baseline + 1
- thread_id, text, role = client.text_appends[-1]
- assert thread_id == "thread-1"
- assert role == "developer"
- assert "900 ms" in text
- # One note per interrupt, never a repeat on the next boundary.
- await session.truncate(audio_end_ms=900)
- assert len(client.text_appends) == baseline + 1
- await session.close()
-
-
-async def test_startup_context_never_authorizes_a_response() -> None:
- """Atomic startup configuration must not buy the model a spoken turn."""
- client = _Client(
- [
- _Notification(
- "thread/realtime/itemAdded",
- {"threadId": "thread-1", "item": {"type": "response.created"}},
- ),
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "text": "Understood.",
- },
- ),
- _Notification(
- "thread/realtime/itemAdded",
- {"threadId": "thread-1", "item": {"type": "response.done"}},
- ),
- ]
- )
- session = await _provider(
- client, input_transcriber_factory=lambda: _StubEndpointer(speaking=False)
- ).open_session(
- RealtimeSessionConfig(
- instructions="You are Nova, the user's own assistant.",
- history=({"role": "user", "text": "Earlier question"},),
- language_is_pinned=True,
- )
- )
-
- assert client.text_appends == []
- _thread_id, start = client.realtime_starts[0]
- assert "You are Nova" in start["trusted_prompt"]
- assert codex_subscription_mod._language_pin_text("en") in start["trusted_prompt"]
- assert start["initial_items"] == [{"role": "user", "text": "Earlier question"}]
-
- events = [event async for event in session.receive()]
-
- # No microphone energy stands behind this answer, and a configuration
- # write is not consent to speak - so it is refused, exactly like any other
- # ungrounded turn.
- assert [event.text for event in events if event.type == "output_transcript_delta"] == []
- await session.close()
-
-
-async def test_the_language_pin_never_authorizes_a_response() -> None:
- """Changing the reply language is configuration, not a request to speak.
-
- The pin travels as the same ``appendText`` write as an announcement, so it
- is the one place where a permit would be easiest to grant by accident -
- and it would hand the model an authorized ungrounded turn on every
- language change.
- """
- client = _Client(
- [
- _Notification(
- "thread/realtime/transcript/done",
- {"threadId": "thread-1", "role": "assistant", "text": "Verstanden."},
- ),
- ]
- )
- session = await _provider(
- client, input_transcriber_factory=lambda: _StubEndpointer(speaking=False)
- ).open_session(RealtimeSessionConfig())
- await session.update_session(language="de")
-
- events = [event async for event in session.receive()]
-
- assert [event.text for event in events if event.type == "output_transcript_delta"] == []
- await session.close()
-
-
-async def test_a_barge_splice_is_sequenced_behind_a_local_boundary() -> None:
- """Live 2026-08-06 17:39/17:41: a cut answer's replacement opened 15-140 ms
- after the previous response's audio and spliced RAW into the one playback
- stream (no boundary between them - the barge closes silently). The
- adapter now closes the spliced-over response with a local turn boundary
- BEFORE the new response's text/audio flows, and counts the sequencing so
- the postmortem can prove it happened.
- """
- transcriber = _ScheduledInputTranscriber(
- [
- (0.02, InputTranscriptEvent(kind="speech_started")),
- (
- 0.0,
- InputTranscriptEvent(kind="transcript", text="Hello", is_final=True),
- ),
- # The interrupting user's own follow-up grounds response 2.
- (0.25, InputTranscriptEvent(kind="speech_started")),
- (
- 0.0,
- InputTranscriptEvent(kind="transcript", text="And again", is_final=True),
- ),
- ]
- )
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.1,
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": "First answer",
- },
- ),
- ),
- (
- 0.5,
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": "Second answer",
- },
- ),
- ),
- ]
- )
- session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
- RealtimeSessionConfig()
- )
-
- events = []
- async with asyncio.timeout(5.0):
- async for event in session.receive():
- events.append(event)
- text = event.text or ""
- if event.type == "output_transcript_delta" and "First" in text:
- # The user talks over the answer: the barge-in cuts response 1
- # WITHOUT any boundary event of its own.
- await session.interrupt()
- if event.type == "output_transcript_delta" and "Second" in text:
- break
-
- deltas = [i for i, event in enumerate(events) if event.type == "output_transcript_delta"]
- first_idx = next(
- i
- for i, event in enumerate(events)
- if event.type == "output_transcript_delta" and "First" in (event.text or "")
- )
- second_idx = next(
- i
- for i, event in enumerate(events)
- if event.type == "output_transcript_delta" and "Second" in (event.text or "")
- )
- between = [event.type for event in events[first_idx:second_idx]]
- assert "turn_complete" in between, (
- "the spliced-over response must close behind a local boundary before "
- f"the new one speaks; saw {between} (deltas at {deltas})"
- )
- assert session.diagnostics().get("sequenced_boundaries", 0) == 1
- await session.close()
-
-
-async def test_the_standing_directive_is_reasserted_on_every_delivery() -> None:
- """A rule stated once at open does not hold on this channel (three live
- calls, 2026-08-05; probe round 1, 2026-08-06), while the per-turn
- language pin demonstrably does - repetition is what makes a rule real
- here. The standing directive must therefore ride EVERY delivery, exactly
- once per payload, even when nothing else changed."""
- client = _Client()
- session = await _provider(client).open_session(RealtimeSessionConfig())
- baseline = len(client.text_appends)
-
- rule = "SPEAK AS ONE VOICE ONLY."
- await session.update_session(instructions="PERSONA BLOCK", standing_directive=rule)
- await session.update_session(instructions="PERSONA BLOCK", standing_directive=rule)
-
- payloads = [text for _, text, _ in client.text_appends[baseline:]]
- assert len(payloads) == 2, "an unchanged turn still delivers the rule"
- for payload in payloads:
- assert payload.count(rule) == 1, payload
- await session.close()
-
-
-async def test_an_unsolicited_opening_never_plays_on_a_grounded_host() -> None:
- """Maintainer live test 2026-08-08: the bounded-greeting compromise lost —
- what played was the model echoing the user's own words and acknowledging
- itself ("geht ab? ... Okay."). Policy now mirrors the zero-role-play
- control adapter: before the call's first user FINAL, nothing unsolicited
- plays at all; the answer the question earns flows right after the final
- (the refused-open response is re-judged immediately, never after the
- stale window)."""
- loud = (1000).to_bytes(2, "little", signed=True) * 480
- transcriber = _ScheduledInputTranscriber(
- [
- (0.02, InputTranscriptEvent(kind="speech_started")),
- (
- 0.55,
- InputTranscriptEvent(kind="transcript", text="What is up?", is_final=True),
- ),
- ]
- )
- endpoint = _FakeAudioEndpoint(
- output_schedule=[
- # The server's greeting monologue, streaming BEFORE any final.
- (0.05, loud),
- (0.10, loud),
- (0.10, loud),
- (0.15, loud),
- # ...and the frames it keeps sending after the final landed.
- (0.30, loud),
- (0.05, loud),
- ]
- )
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.8,
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": "The real answer.",
- },
- ),
- ),
- ]
- )
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- events = []
- final_seen = False
- audio_before_final = 0
- audio_after_final = 0
- async with asyncio.timeout(5.0):
- async for event in session.receive():
- events.append(event)
- if event.type == "input_transcript" and event.is_final:
- final_seen = True
- elif event.type == "audio_delta":
- if final_seen:
- audio_after_final += 1
- else:
- audio_before_final += 1
- if event.type == "output_transcript_delta" and "real answer" in (event.text or ""):
- break
-
- assert audio_before_final == 0, (
- "an unsolicited opening reached the surface before the first final"
- )
- assert audio_after_final > 0, "the re-judged response after the final must play"
- assert session.diagnostics().get("opening_responses_bounded", 0) == 0, (
- "grounded hosts refuse the opener outright; the bound is the recognizer-less fallback only"
- )
- await session.close()
-
-
-async def test_a_final_rejudges_the_open_refused_response_immediately() -> None:
- """The far end often starts answering before the local final lands. That
- response is (correctly) refused while ungrounded - but once the final
- arrives, waiting out the stale-refusal window would eat the answer. The
- final closes the refusal on the spot, and the next frame is granted."""
- loud = (1000).to_bytes(2, "little", signed=True) * 480
- transcriber = _ScheduledInputTranscriber(
- [
- (0.02, InputTranscriptEvent(kind="speech_started")),
- (
- 0.25,
- InputTranscriptEvent(kind="transcript", text="Quick one?", is_final=True),
- ),
- ]
- )
- endpoint = _FakeAudioEndpoint(
- output_schedule=[
- (0.05, loud), # pre-final: refused (opens the refused response)
- (0.35, loud), # post-final: must be re-judged and granted
- (0.05, loud),
- ]
- )
- client = _Client()
- # Keep the notification stream OPEN past the collection window: an
- # exhausted subscription ends the stream and takes the receive loop
- # with it.
- client.subscription = _ScheduledSubscription(
- [
- (
- 5.0,
- _Notification(
- "thread/realtime/transcript/delta",
- {"threadId": "thread-1", "role": "assistant", "delta": "."},
- ),
- ),
- ]
- )
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- events = await _collect_until(session, stop_after=2, kind="audio_delta", timeout_s=2.0)
-
- audio_events = [e for e in events if e.type == "audio_delta"]
- assert len(audio_events) == 2, (
- "the post-final frames must flow without waiting out the "
- f"stale-refusal window; saw {len(audio_events)}"
- )
- await session.close()
-
-
-async def test_a_late_server_user_caption_does_not_split_the_active_answer() -> None:
- """A second transcript source is not a second response boundary.
-
- Live 2026-08-09 20:47: the locally grounded final opened the real answer,
- then ChatGPT-Live's slower caption for the same microphone audio arrived
- while that answer was streaming. Closing the response on that caption
- fabricated a new response identity for the next PCM frame, refused the
- rest as ungrounded, and left the user waiting 15 seconds for no audio.
- """
- loud = (1000).to_bytes(2, "little", signed=True) * 480
- transcriber = _ScheduledInputTranscriber(
- [
- (0.01, InputTranscriptEvent(kind="speech_started")),
- (
- 0.02,
- InputTranscriptEvent(
- kind="transcript",
- text="What is up?",
- is_final=True,
- ),
- ),
- ]
- )
- endpoint = _FakeAudioEndpoint(
- output_schedule=[
- (0.10, loud),
- (0.30, loud),
- (0.10, loud),
- ]
- )
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.15,
- _Notification(
- "thread/realtime/transcript/done",
- {
- "threadId": "thread-1",
- "role": "user",
- "text": "What is up?",
- },
- ),
- ),
- (
- 0.40,
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": "The complete answer.",
- },
- ),
- ),
- ]
- )
- session = await _provider(
- client,
- endpoint=endpoint,
- input_transcriber_factory=lambda: transcriber,
- ).open_session(RealtimeSessionConfig())
-
- events = await _collect_until(
- session,
- stop_after=1,
- kind="output_transcript_delta",
- timeout_s=2.0,
- )
-
- audio = [event for event in events if event.type == "audio_delta"]
- response_ids = {
- event.provider_turn_id
- for event in events
- if event.type in {"audio_delta", "output_transcript_delta"}
- }
- assert len(audio) == 3, "the late duplicate caption must not cut the answer"
- assert len(response_ids) == 1
- assert session.diagnostics().get("response_splices", 0) == 0
- await session.close()
-
-
-async def test_a_discarded_utterance_keeps_its_response_window(
- monkeypatch,
-) -> None:
- """The far end hears a 200 ms "hm?" whatever the local endpointer decides,
- and it answers. Consuming the generation at the discard instant refused
- that answer and cut it (the BUG-124 amplifier); within the grace it now
- plays - and after the grace an unanswered window retires."""
- transcriber = _ScheduledInputTranscriber(
- [
- # Priming exchange: the call opening answers no bare cough under
- # the no-unsolicited policy, so the discard under test is a
- # MID-CALL event like the live BUG-124 amplifier was.
- (0.01, InputTranscriptEvent(kind="speech_started")),
- (
- 0.0,
- InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
- ),
- (0.05, InputTranscriptEvent(kind="speech_started")),
- (
- 0.01,
- InputTranscriptEvent(kind="speech_discarded", voiced_ms=200),
- ),
- ]
- )
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.2,
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": "Did you say something?",
- },
- ),
- ),
- ]
- )
- session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
- RealtimeSessionConfig()
- )
-
- events = await _collect_until(
- session, stop_after=1, kind="output_transcript_delta", timeout_s=2.0
- )
- delivered = [event.text for event in events if event.type == "output_transcript_delta"]
- assert delivered == ["Did you say something?"], (
- "the answer to a heard-but-discarded sound must play inside the grace"
- )
- await session.close()
-
-
-async def test_an_unanswered_discard_window_expires(monkeypatch) -> None:
- monkeypatch.setattr(codex_subscription_mod, "_DISCARDED_UTTERANCE_GRACE_S", 0.05)
- transcriber = _ScheduledInputTranscriber(
- [
- # Priming exchange: the call opening answers no bare cough under
- # the no-unsolicited policy, so the discard under test is a
- # MID-CALL event like the live BUG-124 amplifier was.
- (0.01, InputTranscriptEvent(kind="speech_started")),
- (
- 0.0,
- InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
- ),
- (0.05, InputTranscriptEvent(kind="speech_started")),
- (
- 0.01,
- InputTranscriptEvent(kind="speech_discarded", voiced_ms=200),
- ),
- ]
- )
- client = _Client()
- client.subscription = _ScheduledSubscription(
- [
- (
- 0.4,
- _Notification(
- "thread/realtime/transcript/delta",
- {
- "threadId": "thread-1",
- "role": "assistant",
- "delta": "A late invented answer.",
- },
- ),
- ),
- ]
- )
- session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
- RealtimeSessionConfig()
- )
-
- events = await _collect_until(
- session, stop_after=1, kind="output_transcript_delta", timeout_s=1.5
- )
- delivered = [event.text for event in events if event.type == "output_transcript_delta"]
- assert delivered == [], "past the grace a discarded utterance grounds nothing"
- await session.close()
-
-
-def test_readback_render_budget_is_declared() -> None:
- """A delegate readback on this transport is spoken by ChatGPT-Live, whose
- audio lags its own start (7.4 s scrub-hold measured 2026-08-05). Without a
- declared budget the session's 2.5 s hosted floor governed, so the surface
- fallback took delegated answers in the wrong voice or withheld them
- entirely (AP-21: a declared capability, never a provider-name check)."""
- assert CodexSubscriptionRealtimeProvider.readback_render_budget_s == 12.0
- assert CodexSubscriptionRealtimeProvider.readback_render_budget_s > 2.5, (
- "the declared budget must beat the shared hosted floor"
- )
-
-
-class _DyingTranscriber(_StubEndpointer):
- """Local recognizer whose event stream dies on first read."""
-
- def __init__(self) -> None:
- super().__init__(speaking=True)
-
- async def next_event(self): # noqa: ANN202 - test protocol
- raise RuntimeError("recognizer stream died")
-
-
-_LOUD_FRAME = (1000).to_bytes(2, "little", signed=True) * 480
-
-
-async def test_every_ungrounded_response_is_bounded(monkeypatch) -> None:
- """F5a: bounding only the opener left responses #2..n unbounded whenever
- the recognizer was absent or dead — the regime where the two-AIs
- self-talk loop ran unopposed and past grounded-path fixes 'did not
- stick'. Every failopen response now keeps the same coarse bound."""
- monkeypatch.setattr(codex_subscription_mod, "_OPENING_RESPONSE_MAX_S", 0.05)
- client = _Client()
- client.subscription = _keeps_stream_open()
- endpoint = _FakeAudioEndpoint(
- output_schedule=(
- # Response 1: second chunk ages past the bound.
- (0.0, _LOUD_FRAME),
- (0.1, _LOUD_FRAME),
- # Response 2: same shape — previously unbounded.
- (0.1, _LOUD_FRAME),
- (0.1, _LOUD_FRAME),
- )
- )
- session = await _provider(client, endpoint=endpoint).open_session(RealtimeSessionConfig())
-
- events = await _collect_until(session, stop_after=2, kind="turn_complete", timeout_s=3.0)
-
- assert [event.type for event in events].count("turn_complete") == 2
- diag = session.diagnostics()
- assert diag.get("opening_responses_bounded", 0) == 1
- assert diag.get("ungrounded_responses_bounded", 0) == 1, (
- "the second ungrounded response must be bounded exactly like the opener"
- )
- await session.close()
-
-
-async def test_recognizer_rebuild_restores_grounding(monkeypatch) -> None:
- """F5b: a dead recognizer stream is no longer a one-way latch. The
- rebuild reuses the ordinary build path (process-wide STT cache), so the
- call regains its grounding source instead of running ungrounded until
- hangup."""
- monkeypatch.setattr(codex_subscription_mod, "_RECOGNIZER_REBUILD_BACKOFF_S", 0.0)
- replacements = [
- _DyingTranscriber(),
- _ScriptedInputTranscriber(
- [
- InputTranscriptEvent(kind="speech_started"),
- InputTranscriptEvent(kind="transcript", text="Hello again.", is_final=True),
- ]
- ),
- ]
- client = _Client()
- client.subscription = _keeps_stream_open()
- session = await _provider(
- client,
- input_transcriber_factory=lambda: replacements.pop(0),
- ).open_session(RealtimeSessionConfig())
-
- events = await _collect_until(session, stop_after=1, kind="input_transcript", timeout_s=3.0)
-
- finals = [event for event in events if event.type == "input_transcript"]
- assert [event.text for event in finals] == ["Hello again."], (
- "the rebuilt recognizer must ground turns again"
- )
- assert not [event for event in events if event.type == "error"], (
- "a recovered stream death deserves no surface notice"
- )
- diag = session.diagnostics()
- assert diag.get("recognizer_rebuild_attempts", 0) == 1
- assert diag.get("recognizer_rebuilds_restored", 0) == 1
- await session.close()
-
-
-async def test_exhausted_rebuilds_degrade_out_loud_exactly_once(
- monkeypatch,
-) -> None:
- """F5a+F5b: only after both rebuilds are spent does the call enter the
- bounded ungrounded regime — and it says so on the surface exactly once
- (AP-30), instead of the silent one-way latch that hid the degradation."""
- monkeypatch.setattr(codex_subscription_mod, "_RECOGNIZER_REBUILD_BACKOFF_S", 0.0)
- client = _Client()
- client.subscription = _keeps_stream_open()
- session = await _provider(
- client,
- input_transcriber_factory=_DyingTranscriber,
- ).open_session(RealtimeSessionConfig())
-
- events = await _collect_until(session, stop_after=1, kind="error", timeout_s=3.0)
-
- notices = [event for event in events if event.type == "error"]
- assert len(notices) == 1
- assert "stopped during this" in str(notices[0].error)
- assert notices[0].recoverable is True
- diag = session.diagnostics()
- assert diag.get("recognizer_rebuild_attempts", 0) == 2
- assert diag.get("recognizer_rebuilds_restored", 0) == 2
- assert diag.get("grounding_unavailable_notices", 0) == 1
- assert session._local_grounding_ok is False
- await session.close()
-
-
-async def test_failed_rebuilds_also_end_in_one_notice(monkeypatch) -> None:
- """The rebuild that cannot even BUILD (factory returns None) retries and
- then reports the same single degradation notice as a dying stream."""
- monkeypatch.setattr(codex_subscription_mod, "_RECOGNIZER_REBUILD_BACKOFF_S", 0.0)
- replacements: list = [_DyingTranscriber()]
- client = _Client()
- client.subscription = _keeps_stream_open()
- session = await _provider(
- client,
- input_transcriber_factory=lambda: replacements.pop(0) if replacements else None,
- ).open_session(RealtimeSessionConfig())
-
- events = await _collect_until(session, stop_after=1, kind="error", timeout_s=3.0)
-
- notices = [event for event in events if event.type == "error"]
- assert len(notices) == 1
- assert "could not be rebuilt" in str(notices[0].error)
- diag = session.diagnostics()
- assert diag.get("recognizer_rebuild_attempts", 0) == 2
- assert diag.get("recognizer_rebuilds_restored", 0) == 0
- assert diag.get("grounding_unavailable_notices", 0) == 1
- await session.close()
-
-
-async def test_a_failed_recognizer_build_is_announced_at_session_start() -> None:
- """F5a: a call whose recognizer BUILD failed used to degrade with only a
- build-time log line — the silently disarmed grounding gate. The surface
- now hears about it before the first frame, exactly once."""
- session = codex_subscription_mod._CodexSubscriptionRealtimeSession(
- client=_Client(),
- subscription=_Subscription(),
- thread_id="thread-1",
- answer_sdp="v=0\r\nanswer",
- audio_endpoint=_FakeAudioEndpoint(),
- input_transcriber=None,
- grounding_unavailable_reason="RuntimeError: no STT backend",
- )
-
- events = []
- async for event in session.receive():
- events.append(event)
- if len(events) >= 2:
- break
-
- assert events[0].type == "error"
- assert events[0].recoverable is True
- assert "RuntimeError: no STT backend" in str(events[0].error)
- assert "bounded" in str(events[0].error)
- assert session.diagnostics().get("grounding_unavailable_notices", 0) == 1
- await session.close()
-
-
-async def test_an_injected_none_recognizer_stays_silent() -> None:
- """A caller that explicitly builds the session without a recognizer (every
- test in this file, and any embedder that owns its own STT story) is a
- choice, not a degradation — no start-of-call notice."""
- client = _Client()
- session = await _provider(client).open_session(RealtimeSessionConfig())
-
- events = [event async for event in session.receive()]
-
- assert not [
- event
- for event in events
- if event.type == "error" and "speech recognition is unavailable" in str(event.error)
- ]
- await session.close()
-
-
-def test_a_recognizer_build_failure_carries_its_reason(monkeypatch) -> None:
- """The reason travels to the session so the surface notice can name it."""
- real_import = codex_subscription_mod.importlib.import_module
-
- def _refusing_import(name, *args, **kwargs):
- if name == "jarvis.realtime.input_transcription":
- raise RuntimeError("no usable STT backend")
- return real_import(name, *args, **kwargs)
-
- monkeypatch.setattr(codex_subscription_mod.importlib, "import_module", _refusing_import)
- provider = CodexSubscriptionRealtimeProvider()
-
- transcriber, reason = provider._build_input_transcriber_outcome(
- SimpleNamespace(input_language="de")
- )
-
- assert transcriber is None
- assert reason == "RuntimeError: no usable STT backend"
-
-
-def test_session_language_reaches_the_recognizer(monkeypatch) -> None:
- """F5c happy path: the resolved session input language is threaded into
- the local recognizer, which pins it on the STT config it builds."""
- built = []
-
- class _NewTranscriber:
- def __init__(self, *, sample_rate: int, language=None) -> None:
- built.append((sample_rate, language))
-
- fake_module = SimpleNamespace(LocalInputTranscriber=_NewTranscriber)
- real_import = codex_subscription_mod.importlib.import_module
- monkeypatch.setattr(
- codex_subscription_mod.importlib,
- "import_module",
- lambda name, *a, **k: (
- fake_module
- if name == "jarvis.realtime.input_transcription"
- else real_import(name, *a, **k)
- ),
- )
- provider = CodexSubscriptionRealtimeProvider()
-
- provider._build_input_transcriber(SimpleNamespace(input_language="de"))
- provider._build_input_transcriber(SimpleNamespace(input_language="auto"))
-
- assert built == [
- (codex_subscription_mod._INPUT_RATE, "de"),
- (
- codex_subscription_mod._INPUT_RATE,
- None,
- ),
- ], "an explicit language is passed; 'auto' keeps the configured one"
-
-
-def test_language_kwarg_rejection_warns_exactly_once(monkeypatch, caplog) -> None:
- """F5c: the tolerance probe for an out-of-tree recognizer without the
- ``language`` kwarg stays, but its failure is a one-shot WARNING — the
- silently swallowed capability (a DEBUG line) is how the un-pinned session
- language survived unreported (AP-30)."""
- caplog.set_level(logging.DEBUG)
- monkeypatch.setattr(codex_subscription_mod, "_language_kwarg_rejected_warned", False)
-
- class _OldTranscriber:
- def __init__(self, *, sample_rate: int) -> None:
- self.sample_rate = sample_rate
-
- fake_module = SimpleNamespace(LocalInputTranscriber=_OldTranscriber)
- real_import = codex_subscription_mod.importlib.import_module
- monkeypatch.setattr(
- codex_subscription_mod.importlib,
- "import_module",
- lambda name, *a, **k: (
- fake_module
- if name == "jarvis.realtime.input_transcription"
- else real_import(name, *a, **k)
- ),
- )
- provider = CodexSubscriptionRealtimeProvider()
- cfg = SimpleNamespace(input_language="de")
-
- first = provider._build_input_transcriber(cfg)
- second = provider._build_input_transcriber(cfg)
-
- assert isinstance(first, _OldTranscriber)
- assert isinstance(second, _OldTranscriber), (
- "the probe must fall back, never lose the grounding source"
- )
- rejections = [
- record
- for record in caplog.records
- if "does not accept a session language" in record.getMessage()
- ]
- assert [record.levelno for record in rejections] == [
- logging.WARNING,
- logging.DEBUG,
- ]
-
-
-class _RosterClient(_Client):
- """Client whose server publishes a live voice roster (codex-cli 0.147)."""
-
- def __init__(self, *args, **kwargs) -> None:
- super().__init__(*args, **kwargs)
- self.roster_requests: list[str] = []
-
- async def realtime_list_voices(self, thread_id: str) -> dict:
- self.roster_requests.append(thread_id)
- return {
- "v1": ["Nova"],
- "v2": ["cove"],
- "defaultV1": "nova",
- "defaultV2": "cove",
- }
-
-
-class _RosterRpcError(Exception):
- """Duck-typed stand-in for CodexAppServerRPCError."""
-
- def __init__(self, message: str, code: int) -> None:
- super().__init__(message)
- self.code = code
-
-
-class _RosterRejectingClient(_Client):
- async def realtime_list_voices(self, thread_id: str) -> dict:
- del thread_id
- raise _RosterRpcError("Method not found", -32601)
-
-
-class _RosterDeadTransportClient(_Client):
- async def realtime_list_voices(self, thread_id: str) -> dict:
- del thread_id
- raise RuntimeError("app-server transport is gone")
-
-
-async def test_the_live_voice_roster_extends_the_audited_static_set() -> None:
- """The server's own listVoices answer is authoritative when readable, so
- a voice the nine-name frozenset never heard of still validates."""
- client = _RosterClient()
- session = await _provider(client).open_session(RealtimeSessionConfig(voice="nova"))
-
- assert client.roster_requests == ["thread-1"]
- _thread_id, start = client.realtime_starts[0]
- assert start["voice"] == "nova"
- await session.close()
-
-
-async def test_a_rejected_list_voices_falls_back_to_the_static_roster() -> None:
- """An older server build without the method (JSON-RPC refusal, has a
- ``code``) degrades to the audited nine-voice frozenset — capability
- probed, never version-string-gated in this adapter (AP-21/AP-22)."""
- session = await _provider(_RosterRejectingClient()).open_session(
- RealtimeSessionConfig(voice="cove")
- )
- await session.close()
-
- with pytest.raises(RuntimeError, match="unsupported voice"):
- await _provider(_RosterRejectingClient()).open_session(RealtimeSessionConfig(voice="nova"))
-
-
-async def test_a_transport_failure_during_list_voices_is_not_fatal(monkeypatch, caplog) -> None:
- """The roster refresh is ADVISORY: it only ever widens a roster that
- already works, so a timeout or a dead transport must fall back to the
- audited static set instead of aborting an open whose thread is already
- running. A voice the SERVER refuses still fails loudly at realtime_start."""
- caplog.set_level(logging.DEBUG)
- monkeypatch.setattr(codex_subscription_mod, "_voice_roster_probe_warned", False)
-
- session = await _provider(_RosterDeadTransportClient()).open_session(
- RealtimeSessionConfig(voice="cove")
- )
- await session.close()
-
- second = await _provider(_RosterDeadTransportClient()).open_session(
- RealtimeSessionConfig(voice="cove")
- )
- await second.close()
-
- failures = [
- record
- for record in caplog.records
- if "could not answer thread/realtime/listVoices" in record.getMessage()
- ]
- assert [record.levelno for record in failures] == [
- logging.WARNING,
- logging.DEBUG,
- ], "one-shot warning, then quiet — advisory, but never swallowed (AP-30)"
-
-
-async def test_a_transport_failure_during_list_voices_keeps_the_static_bound() -> None:
- """Falling back is not the same as accepting anything: a voice outside
- the audited static roster is still refused when the live one is unreadable."""
- with pytest.raises(RuntimeError, match="unsupported voice"):
- await _provider(_RosterDeadTransportClient()).open_session(
- RealtimeSessionConfig(voice="nova")
- )
-
-
-class _InstructionSlotClient(_Client):
- """Client that declares AND transmits the 0.147 realtimeStartInstructions."""
-
- def realtime_start_instructions_supported(self) -> bool:
- return True
-
- async def realtime_start(
- self,
- thread_id: str,
- *,
- realtime_start_instructions: str | None = None,
- **kwargs,
- ):
- kwargs["realtime_start_instructions"] = realtime_start_instructions
- self.realtime_starts.append((thread_id, kwargs))
- return SimpleNamespace(
- response=self.start_response,
- answer_sdp="v=0\r\nanswer",
- )
-
-
-class _WithheldInstructionSlotClient(_InstructionSlotClient):
- """Declares the keyword but is bound to a binary that never sends it."""
-
- def realtime_start_instructions_supported(self) -> bool:
- return False
-
-
-class _UnprobedInstructionSlotClient(_InstructionSlotClient):
- """Declares the keyword and offers no capability probe at all."""
-
- realtime_start_instructions_supported = None
-
-
-async def test_startup_contract_rides_the_instruction_slot_when_transmitted() -> None:
- """When the client declares realtime_start_instructions AND confirms it
- transmits the field, the startup contract travels as SESSION instructions
- instead of a trusted first prompt — injected prompt context is what the
- model audibly acknowledged mid-open."""
- client = _InstructionSlotClient()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(instructions="You are Nova.")
- )
-
- _thread_id, start = client.realtime_starts[0]
- assert start["trusted_prompt"] == ""
- assert "You are Nova." in start["realtime_start_instructions"]
- assert "Speak only the assistant side" in start["realtime_start_instructions"]
- await session.close()
-
-
- "client_factory",
- [_WithheldInstructionSlotClient, _UnprobedInstructionSlotClient],
- ids=["probe-says-withheld", "no-probe-at-all"],
-)
-async def test_startup_contract_stays_on_the_prompt_when_not_transmitted(
- client_factory,
-) -> None:
- """Declaration is not transmission. A client bound to a binary that drops
- the field — and one that cannot even answer the question — must keep the
- trusted prompt: blanking it there left the whole call with no persona,
- because the pre-marked context baseline suppresses every later re-send."""
- client = client_factory()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(instructions="You are Nova.")
- )
-
- _thread_id, start = client.realtime_starts[0]
- assert start["realtime_start_instructions"] is None
- assert "You are Nova." in start["trusted_prompt"]
- await session.close()
-
-
-async def test_startup_contract_stays_on_the_prompt_without_the_slot() -> None:
- """A client that does not DECLARE the parameter by name keeps the proven
- trusted-prompt path — a ``**kwargs`` sink would swallow the contract
- without sending it, the exact silent capability loss AP-30 forbids."""
- client = _Client()
- session = await _provider(client).open_session(
- RealtimeSessionConfig(instructions="You are Nova.")
- )
-
- _thread_id, start = client.realtime_starts[0]
- assert "realtime_start_instructions" not in start
- assert "You are Nova." in start["trusted_prompt"]
- await session.close()
-
-
-async def test_multibyte_startup_history_stays_under_the_server_byte_limit() -> None:
- """The app server bounds ``initialItems`` by UTF-8 BYTES, so the adapter
- must trim by bytes too. Trimming by characters let CJK history pass here
- at up to four bytes per character and then fail realtime_start with
- "startup history is too large" — precisely on the mid-call rebuild whose
- job is to restore a call quietly."""
- history = tuple(
- {"role": "user" if index % 2 == 0 else "assistant", "text": "\u5b9f\u884c" * 1_000}
- for index in range(codex_subscription_mod._HISTORY_MAX_ITEMS)
- )
- client = _Client()
- session = await _provider(client).open_session(RealtimeSessionConfig(history=history))
-
- _thread_id, start = client.realtime_starts[0]
- items = start["initial_items"]
- assert items, "the newest turns must still be seeded, not dropped wholesale"
- total_bytes = sum(len(item["text"].encode("utf-8")) for item in items)
- assert total_bytes <= _MAX_REALTIME_INITIAL_TEXT_BYTES, (
- "the emitted history must fit the limit the server itself validates"
- )
- assert total_bytes <= codex_subscription_mod._HISTORY_MAX_BYTES
- assert all(item["text"] == history[0]["text"][:2_000] for item in items)
- await session.close()
-
-
-def test_ascii_startup_history_keeps_its_proven_bound() -> None:
- """The byte bound is the same number the character bound used to be, so
- plain-ASCII history is trimmed exactly as before — no silent regression
- in how much context a normal call carries."""
- history = tuple(
- {"role": "user", "text": "a" * 2_000}
- for _ in range(codex_subscription_mod._HISTORY_MAX_ITEMS)
- )
-
- items = codex_subscription_mod._history_initial_items(history)
-
- assert len(items) == codex_subscription_mod._HISTORY_MAX_BYTES // 2_000
diff --git a/tests/unit/realtime/test_speak_request_parity.py b/tests/unit/realtime/test_speak_request_parity.py
deleted file mode 100644
index 973596234e..0000000000
--- a/tests/unit/realtime/test_speak_request_parity.py
+++ /dev/null
@@ -1,74 +0,0 @@
-"""The developer-message silence rule and the speak-request prompts must agree.
-
-The Codex base instructions tell the model that developer messages are silent
-configuration — with ONE exception, named by its exact opening sentence. Every
-prompt whose entire purpose is to be spoken (announcements, late action
-results, the direct-tool retry) must therefore open with that exact sentence,
-or the categorical silence rule mutes it: a When-Then task completes, Jarvis
-injects the announcement, and the user hears nothing (independent review
-2026-08-05, finding S1).
-"""
-
-from __future__ import annotations
-
-import jarvis.plugins.realtime.codex_subscription as codex_subscription_mod
-import jarvis.realtime.session as session_mod
-
-
-def test_base_instructions_quote_the_exact_speak_request_opener() -> None:
- base = codex_subscription_mod._THREAD_BASE_INSTRUCTIONS
- assert f"'{session_mod.SPEAK_REQUEST_OPENER}'" in base
- # The rule itself must exist and stay scoped to CONFIGURATION messages.
- assert "silent configuration" in base
- assert "configuration message's arrival" in base
-
-
-def test_session_channel_carries_the_rule_AND_its_exception_together() -> None:
- """Both halves must ride the channel the voice model provably reads.
-
- Shipping the silence half in the per-session block while the exception
- sat only in the thread-start instructions would mute announcements and
- late action results all over again (independent review C1: the one-
- speaker directive's "wait silently" plus the inline "never acknowledge"
- headers outvoted an exception the voice may never see).
- """
- directive = session_mod._ONE_SPEAKER_DIRECTIVE
- assert "silent configuration" in directive
- assert f"'{session_mod.SPEAK_REQUEST_OPENER}'" in directive
- # And the whole thing reaches the assembled session block.
- block = session_mod._session_instructions("en")
- assert f"'{session_mod.SPEAK_REQUEST_OPENER}'" in block
-
-
-def test_every_speak_request_prompt_opens_with_the_exception_sentence() -> None:
- opener = session_mod.SPEAK_REQUEST_OPENER
- prompts = (
- session_mod._external_update_prompt(
- "Task finished.", language="en", kind="announcement"
- ),
- session_mod._delegate_result_prompt(
- "The window is open.", language="en", success=True
- ),
- session_mod._delegate_result_prompt(
- "It failed.", language="en", success=False, late=True
- ),
- session_mod._direct_tool_result_retry_prompt(language="en"),
- # Unreachable on the Codex adapter today (the bridge line prefers
- # send_speech there), but the same silence-rule class the moment a
- # transport lacks that preference — the reviewer's latent-flank note.
- session_mod._delegate_bridge_prompt(
- language="en", exact_text="One moment please."
- ),
- )
- for prompt in prompts:
- assert prompt.startswith(opener)
-
-
-def test_configuration_payloads_never_carry_the_speak_request_opener() -> None:
- """The exception must stay reserved for genuine delivery orders."""
- opener = session_mod.SPEAK_REQUEST_OPENER
- assert opener not in codex_subscription_mod._language_pin_text("de")
- assert opener not in codex_subscription_mod._THREAD_DEVELOPER_INSTRUCTIONS
- assert opener not in session_mod._DELEGATE_ROLE_DIRECTIVE_HANDOFF
- assert opener not in session_mod._DELEGATE_REQUIRED_DIRECTIVE
- assert opener not in session_mod._DELEGATE_PENDING_DIRECTIVE
diff --git a/tests/unit/test_provider_spec.py b/tests/unit/test_provider_spec.py
index b98e7a4936..06daca382f 100644
--- a/tests/unit/test_provider_spec.py
+++ b/tests/unit/test_provider_spec.py
@@ -88,8 +88,10 @@ def test_get_spec_lookup() -> None:
assert get_spec("does-not-exist") is None
-def test_codex_subscription_realtime_is_visible_in_provider_catalog() -> None:
- assert "codex-subscription-realtime" in {spec.id for spec in PROVIDERS}
+def test_codex_subscription_realtime_is_removed_from_provider_catalog() -> None:
+ """Removed 2026-08-10 with its adapter; the stable subscription voice
+ runs as a classic-pipeline profile, not a realtime card."""
+ assert "codex-subscription-realtime" not in {spec.id for spec in PROVIDERS}
def test_groq_stt_is_last_and_not_recommended() -> None:
diff --git a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py
deleted file mode 100644
index 7ee98aa639..0000000000
--- a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py
+++ /dev/null
@@ -1,1307 +0,0 @@
-from __future__ import annotations
-
-from types import SimpleNamespace
-
-import pytest
-from fastapi import HTTPException
-
-from jarvis.ui.web import provider_routes as routes
-from jarvis.ui.web.provider_spec import get_spec, provider_billing
-
-
-class _Status:
- def __init__(self, *, connected: bool, mode: str) -> None:
- self.connected = connected
- self.mode = mode
-
- def to_dict(self) -> dict[str, object]:
- return {
- "installed": True,
- "connected": self.connected,
- "mode": self.mode,
- "message": "Codex status",
- "version": "1.0",
- }
-
-
-def test_codex_subscription_realtime_spec_has_no_api_key_path() -> None:
- spec = get_spec("codex-subscription-realtime")
-
- assert spec is not None
- assert spec.tier == "realtime"
- assert spec.auth_mode == "codex"
- assert spec.secret_keys == ()
- assert provider_billing(spec) == "subscription"
- assert spec.experimental is True
-
-
- ("connected", "mode", "configured"),
- [
- (True, "chatgpt", True),
- (True, "api_key", False),
- (False, "not_connected", False),
- ],
-)
-def test_keyless_codex_readiness_requires_chatgpt_login(
- monkeypatch: pytest.MonkeyPatch,
- connected: bool,
- mode: str,
- configured: bool,
-) -> None:
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
-
- class _Service:
- def __init__(self, *_args, **_kwargs) -> None:
- pass
-
- def status(self) -> _Status:
- return _Status(connected=connected, mode=mode)
-
- monkeypatch.setattr(routes, "CodexAuthService", _Service)
- monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")
- monkeypatch.setattr(routes.cfg_mod, "get_secret", lambda *_args, **_kwargs: None)
- monkeypatch.setattr(
- routes,
- "_is_credential_present",
- lambda *_args, **_kwargs: pytest.fail("keyless Codex must use login status"),
- )
-
- payload = routes._spec_to_payload(
- spec,
- active_brain=None,
- active_tts=None,
- active_stt=None,
- active_realtime=spec.id if configured else None,
- )
-
- assert payload["configured"] is configured
- assert payload["billing"] == "subscription"
- assert payload["codex_status"]["mode"] == mode
- assert payload["cli_installed"] is True
- assert "codex_brain_ready" not in payload
-
-
-def test_authoritative_subscription_probe_overrides_stale_chatgpt_status(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
-
- class _Service:
- def __init__(self, *_args, **_kwargs) -> None:
- pass
-
- def status(self) -> _Status:
- return _Status(connected=True, mode="chatgpt")
-
- monkeypatch.setattr(routes, "CodexAuthService", _Service)
- monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")
- monkeypatch.setattr(routes.cfg_mod, "get_secret", lambda *_args, **_kwargs: None)
-
- payload = routes._spec_to_payload(
- spec,
- active_brain=None,
- active_tts=None,
- active_stt=None,
- active_realtime=None,
- codex_subscription_ready=False,
- )
-
- assert payload["configured"] is False
- assert payload["codex_status"]["connected"] is False
- assert payload["codex_status"]["mode"] == "not_connected"
- assert "not ready" in payload["codex_status"]["message"]
-
-
-async def test_section_health_accepts_keyring_only_chatgpt_login(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis import codex_app_server
-
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
-
- async def ready(_binary_path: str | None = None) -> bool:
- return True
-
- async def healthy_probe(*_args, **_kwargs):
- return SimpleNamespace(status="ok", detail="subscription reachable")
-
- monkeypatch.setattr(codex_app_server, "codex_subscription_login_ready", ready)
- monkeypatch.setattr(routes, "_run_tier_test", healthy_probe)
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": True,
- "mode": "chatgpt",
- "message": "Dedicated ChatGPT subscription voice login is ready.",
- "reason_code": "ready",
- },
- )
- monkeypatch.setattr(
- routes,
- "_is_credential_present",
- lambda *_args, **_kwargs: pytest.fail(
- "section health must use the authoritative app-server auth probe"
- ),
- )
-
- health = await routes._realtime_section_health(
- SimpleNamespace(),
- spec,
- binary_path="codex-custom",
- )
-
- assert health.status == "ok"
- assert health.reason == "ok"
- assert health.subject_id == "codex-subscription-realtime"
-
-
-async def test_realtime_activation_rejects_codex_api_key_mode(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- class _Service:
- def __init__(self, *_args, **_kwargs) -> None:
- pass
-
- def status(self) -> _Status:
- return _Status(connected=True, mode="api_key")
-
- monkeypatch.setattr(routes, "CodexAuthService", _Service)
- monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")
-
- # The route judges this provider by the isolated-profile snapshot, never
- # the ordinary Codex login. An api-key-mode login yields no dedicated
- # ChatGPT-authenticated profile, so the snapshot answers not-connected.
- # Patching the payload keeps this unit test off the real CLI and
- # independent of the host's login state.
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": "Connect the dedicated ChatGPT subscription voice login.",
- "reason_code": "login_required",
- },
- )
-
- with pytest.raises(HTTPException) as caught:
- await routes.realtime_switch(
- routes.SwitchBody(
- provider="codex-subscription-realtime",
- persist=False,
- accept_experimental=True,
- ),
- object(),
- )
-
- assert caught.value.status_code == 409
- # The precise payload diagnosis, never the generic credential sentence.
- assert "dedicated ChatGPT subscription voice login" in str(caught.value.detail)
-
-
-async def test_plan_unsupported_activation_retries_the_live_gate(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """plan_unsupported must reach verify_activation (the only path that can
- CLEAR the sticky block) and answer with the plan diagnosis on re-refusal."""
- from jarvis import codex_app_server
- from jarvis.codex_app_server import CodexSubscriptionPlanUnsupported
-
- monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": "Subscription voice permits only personal ChatGPT accounts.",
- "reason_code": "plan_unsupported",
- },
- )
-
- gate_calls: list[object] = []
- close_calls: list[object] = []
-
- class _Client:
- async def require_chatgpt_login(self) -> None:
- gate_calls.append(self)
- raise CodexSubscriptionPlanUnsupported(
- "Subscription voice permits only personal ChatGPT accounts."
- )
-
- async def close(self) -> None:
- close_calls.append(self)
-
- monkeypatch.setattr(
- codex_app_server,
- "get_shared_codex_app_server",
- lambda *_args, **_kwargs: _Client(),
- )
-
- request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=None, cfg=None)))
- with pytest.raises(HTTPException) as caught:
- await routes.realtime_switch(
- routes.SwitchBody(
- provider="codex-subscription-realtime",
- persist=False,
- accept_experimental=True,
- ),
- request,
- )
-
- assert gate_calls, "the realtime provider gate must re-judge a plan-blocked account"
- assert close_calls == gate_calls
- assert caught.value.status_code == 409
- detail = str(caught.value.detail)
- assert "personal ChatGPT accounts" in detail
- assert "no configured credentials" not in detail
-
-
-async def test_realtime_activation_reports_busy_instead_of_demanding_reconnect(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A transient busy window must not tell the user to redo a working login."""
- release_calls: list[str] = []
-
- async def release_previous_transport() -> None:
- release_calls.append("released")
-
- monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": False,
- "connected": False,
- "mode": "not_connected",
- "message": "Dedicated subscription voice status is being checked or changed.",
- "reason_code": "busy",
- },
- )
- monkeypatch.setattr(
- routes,
- "_release_codex_transports_for_voice_switch",
- release_previous_transport,
- )
-
- with pytest.raises(HTTPException) as caught:
- await routes.realtime_switch(
- routes.SwitchBody(
- provider="codex-subscription-realtime",
- persist=False,
- accept_experimental=True,
- ),
- object(),
- )
-
- assert caught.value.status_code == 409
- detail = str(caught.value.detail)
- assert "being checked" in detail
- assert "Connect or configure" not in detail
- assert release_calls == ["released"]
-
-
-async def test_realtime_activation_reclaims_a_warm_transport_before_retry(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis import codex_app_server
-
- snapshots = [
- {
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": "Subscription voice is busy.",
- "reason_code": "busy",
- },
- {
- "installed": True,
- "connected": True,
- "mode": "chatgpt",
- "message": "ready",
- "reason_code": "ready",
- },
- ]
- release_calls: list[str] = []
-
- async def release_previous_transport() -> None:
- release_calls.append("released")
-
- class _Client:
- async def require_chatgpt_login(self) -> None:
- return None
-
- async def close(self) -> None:
- return None
-
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: snapshots.pop(0),
- )
- monkeypatch.setattr(
- routes,
- "_release_codex_transports_for_voice_switch",
- release_previous_transport,
- )
- monkeypatch.setattr(
- codex_app_server,
- "get_shared_codex_app_server",
- lambda *_args, **_kwargs: _Client(),
- )
- monkeypatch.setattr(
- codex_app_server,
- "set_codex_subscription_activation_block",
- lambda _value: None,
- )
- config = SimpleNamespace(
- codex=SimpleNamespace(binary_path="codex"),
- voice=SimpleNamespace(profile="", mode="realtime"),
- brain=SimpleNamespace(realtime=None),
- )
-
- response = await routes.realtime_switch(
- routes.SwitchBody(
- provider="codex-subscription-realtime",
- persist=False,
- accept_experimental=True,
- ),
- SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=config))),
- )
-
- assert response["profile"] == ""
- assert response["mode"] == "realtime"
- assert release_calls == ["released"]
- assert snapshots == []
-
-
-def test_spec_payload_preserves_the_isolated_snapshot_diagnosis(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The precise setup diagnosis must survive into /api/providers."""
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
- monkeypatch.setattr(routes.cfg_mod, "get_secret", lambda *_args, **_kwargs: None)
-
- payload = routes._spec_to_payload(
- spec,
- active_brain=None,
- active_tts=None,
- active_stt=None,
- active_realtime=None,
- codex_subscription_ready=False,
- codex_subscription_status={
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": "Subscription voice requires Codex CLI codex-cli 0.146.0.",
- "reason_code": "setup_invalid",
- },
- )
-
- assert payload["codex_status"]["reason_code"] == "setup_invalid"
- assert (
- payload["codex_status"]["message"]
- == "Subscription voice requires Codex CLI codex-cli 0.146.0."
- )
-
-
-def test_subscription_status_payload_maps_busy_without_claiming_missing_install(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis import codex_app_server
-
- class _PresenceService:
- def __init__(self, *_args, **_kwargs) -> None:
- pass
-
- def _resolve_binary(self) -> str:
- return "codex"
-
- snapshot = codex_app_server.CodexAppServerCapability(
- available=False,
- chatgpt_authenticated=False,
- binary_path=None,
- version=None,
- reason="Dedicated subscription voice status is being checked or changed.",
- reason_code="busy",
- )
- monkeypatch.setattr(
- codex_app_server,
- "codex_subscription_auth_snapshot",
- lambda _binary_path: snapshot,
- )
- monkeypatch.setattr(routes, "CodexAuthService", _PresenceService)
-
- payload = routes._codex_subscription_status_payload(None)
-
- assert payload["reason_code"] == "busy"
- assert payload["connected"] is False
- # The name of this test is a promise: busy must not read as a missing CLI.
- assert payload["installed"] is True
- assert payload["message"] == (
- "Dedicated subscription voice status is being checked or changed."
- )
-
-
-def test_spec_payload_busy_does_not_claim_missing_cli(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """During busy the card must not render the install prompt via cli_installed."""
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
- monkeypatch.setattr(routes.cfg_mod, "get_secret", lambda *_args, **_kwargs: None)
- monkeypatch.setattr(routes, "_cli_installed", lambda _spec: True)
-
- payload = routes._spec_to_payload(
- spec,
- active_brain=None,
- active_tts=None,
- active_stt=None,
- active_realtime=None,
- codex_subscription_ready=False,
- codex_subscription_status={
- "installed": False,
- "connected": False,
- "mode": "not_connected",
- "message": "Dedicated subscription voice status is being checked or changed.",
- "reason_code": "busy",
- },
- )
-
- assert payload["codex_status"]["reason_code"] == "busy"
- assert payload["cli_installed"] is True
-
-
-def test_status_payload_survives_a_raising_probe(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A raising probe must degrade to busy, not 500 the whole providers screen."""
- from jarvis import codex_app_server
-
- def explode(_binary_path: str | None) -> None:
- raise OSError("cli exploded")
-
- monkeypatch.setattr(codex_app_server, "codex_subscription_auth_snapshot", explode)
-
- payload = routes._codex_subscription_status_payload(None)
-
- assert payload["reason_code"] == "busy"
- assert payload["connected"] is False
- assert "OSError" in payload["message"]
-
-
-async def test_section_health_reports_busy_as_unknown(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A transient busy window is not an amber "needs setup" dot."""
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": False,
- "connected": False,
- "mode": "not_connected",
- "message": "Dedicated subscription voice status is being checked or changed.",
- "reason_code": "busy",
- },
- )
-
- health = await routes._tier_section_health(
- SimpleNamespace(),
- spec,
- binary_path="codex-custom",
- )
-
- assert health.status == "unknown"
- assert health.reason == "busy"
-
-
-async def test_tier_test_judges_the_isolated_voice_profile(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The Test button must never answer from the ordinary Codex login."""
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": True,
- "mode": "chatgpt",
- "message": "Dedicated ChatGPT subscription voice login is ready.",
- "reason_code": "ready",
- },
- )
-
- captured: dict[str, object] = {}
-
- async def capture_run(spec_arg, cfg_arg, **kwargs):
- captured.update(kwargs)
- status_fn = kwargs.get("codex_status")
- assert callable(status_fn)
- return SimpleNamespace(status="ok", detail=status_fn().message)
-
- monkeypatch.setattr(routes._provider_test, "run_provider_test", capture_run)
-
- result = await routes._run_tier_test(spec, SimpleNamespace())
-
- assert result.status == "ok"
- assert "subscription voice login is ready" in result.detail
- assert "codex_status" in captured
-
-
-def test_login_window_keeps_the_cli_reported_as_installed(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """During the minutes-long interactive login the snapshot is silent about
- the CLI; the card must not tell the user to reinstall mid-login."""
- from jarvis import codex_app_server
-
- class _PresenceService:
- def __init__(self, *_args, **_kwargs) -> None:
- pass
-
- def _resolve_binary(self) -> str:
- return "codex"
-
- snapshot = codex_app_server.CodexAppServerCapability(
- available=False,
- chatgpt_authenticated=False,
- binary_path=None,
- version=None,
- reason="Dedicated ChatGPT subscription login is in progress.",
- reason_code="login_in_progress",
- )
- monkeypatch.setattr(
- codex_app_server,
- "codex_subscription_auth_snapshot",
- lambda _binary_path: snapshot,
- )
- monkeypatch.setattr(routes, "CodexAuthService", _PresenceService)
-
- payload = routes._codex_subscription_status_payload(None)
-
- assert payload["reason_code"] == "login_in_progress"
- assert payload["installed"] is True
-
-
-def test_plan_block_turns_a_ready_login_into_plan_unsupported(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """After a refused activation, surfaces must stop claiming ready."""
- from jarvis import codex_app_server
-
- snapshot = codex_app_server.CodexAppServerCapability(
- available=True,
- chatgpt_authenticated=True,
- binary_path="codex",
- version="codex-cli 0.146.0",
- reason="Dedicated ChatGPT login is available.",
- reason_code="ready",
- )
- monkeypatch.setattr(
- codex_app_server,
- "codex_subscription_auth_snapshot",
- lambda _binary_path: snapshot,
- )
- monkeypatch.setattr(
- codex_app_server,
- "_subscription_activation_block",
- "Subscription voice permits only personal ChatGPT accounts.",
- )
-
- payload = routes._codex_subscription_status_payload(None)
-
- assert payload["reason_code"] == "plan_unsupported"
- assert payload["connected"] is False
- assert "personal ChatGPT accounts" in payload["message"]
-
-
-def test_lifecycle_unavailable_does_not_claim_missing_cli(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """An unsupported OS must not render the install prompt for a CLI that
- would not help anyway."""
- from jarvis import codex_app_server
-
- class _PresenceService:
- def __init__(self, *_args, **_kwargs) -> None:
- pass
-
- def _resolve_binary(self) -> str:
- return "codex"
-
- snapshot = codex_app_server.CodexAppServerCapability(
- available=False,
- chatgpt_authenticated=False,
- binary_path=None,
- version=None,
- reason="This operating-system architecture is not approved.",
- reason_code="lifecycle_unavailable",
- )
- monkeypatch.setattr(
- codex_app_server,
- "codex_subscription_auth_snapshot",
- lambda _binary_path: snapshot,
- )
- monkeypatch.setattr(routes, "CodexAuthService", _PresenceService)
-
- payload = routes._codex_subscription_status_payload(None)
-
- assert payload["reason_code"] == "lifecycle_unavailable"
- assert payload["installed"] is True
-
-
-def test_wrong_release_payload_shows_the_install_path(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A wrong codex release must surface the install flow, not a profile
- warning: installed=False drives the pinned npm command on the card."""
- from jarvis import codex_app_server
-
- snapshot = codex_app_server.CodexAppServerCapability(
- available=False,
- chatgpt_authenticated=False,
- binary_path="codex",
- version="codex-cli 0.150.0",
- reason="Subscription voice requires Codex CLI 0.146.0.",
- reason_code="not_installed",
- )
- monkeypatch.setattr(
- codex_app_server,
- "codex_subscription_auth_snapshot",
- lambda _binary_path: snapshot,
- )
-
- payload = routes._codex_subscription_status_payload(None)
-
- assert payload["reason_code"] == "not_installed"
- assert payload["installed"] is False
- assert "requires Codex CLI 0.146.0" in payload["message"]
-
-
-async def test_tier_test_reports_busy_as_transient_not_as_unconfigured(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The Test button must not issue a setup verdict for a transient window."""
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": "Dedicated subscription voice status is being checked or changed.",
- "reason_code": "busy",
- },
- )
-
- result = await routes._run_tier_test(spec, SimpleNamespace())
-
- assert result.status == "rate_limited"
- assert "being checked" in result.detail
-
-
-async def test_tier_test_reports_login_in_progress_as_transient(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """During a running login the Test button must not dissent from the card."""
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": "Dedicated ChatGPT subscription login is in progress.",
- "reason_code": "login_in_progress",
- },
- )
-
- result = await routes._run_tier_test(spec, SimpleNamespace())
-
- assert result.status == "rate_limited"
- assert "login is in progress" in result.detail
-
-
-async def test_section_health_reports_login_in_progress_as_unknown(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": "Dedicated ChatGPT subscription login is in progress.",
- "reason_code": "login_in_progress",
- },
- )
-
- health = await routes._tier_section_health(SimpleNamespace(), spec, binary_path="codex-custom")
-
- assert health.status == "unknown"
- assert health.reason == "login_in_progress"
-
-
- ("reason_code", "message", "expected_fragment"),
- [
- (
- "plan_unsupported",
- "Subscription voice permits only personal ChatGPT accounts.",
- "personal ChatGPT accounts",
- ),
- (
- "lifecycle_unavailable",
- "Interactive subscription-voice login is unavailable on headless Linux.",
- "headless Linux",
- ),
- (
- "not_installed",
- "Subscription voice requires Codex CLI 0.146.0.",
- "requires Codex CLI 0.146.0",
- ),
- ],
-)
-async def test_section_health_hover_names_the_real_remedy(
- monkeypatch: pytest.MonkeyPatch,
- reason_code: str,
- message: str,
- expected_fragment: str,
-) -> None:
- """The amber dot's hover must never say "not connected or configured"
- when the actual remedy is a plan change, another host, or an install."""
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": message,
- "reason_code": reason_code,
- },
- )
-
- health = await routes._tier_section_health(SimpleNamespace(), spec, binary_path="codex-custom")
-
- assert health.status == "needs_setup"
- assert health.reason == reason_code
- assert expected_fragment in health.detail
- assert "not connected or configured" not in health.detail
-
-
-async def test_realtime_activation_asks_to_finish_a_running_login(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": "Dedicated ChatGPT subscription login is in progress.",
- "reason_code": "login_in_progress",
- },
- )
-
- with pytest.raises(HTTPException) as caught:
- await routes.realtime_switch(
- routes.SwitchBody(
- provider="codex-subscription-realtime",
- persist=False,
- accept_experimental=True,
- ),
- object(),
- )
-
- assert caught.value.status_code == 409
- assert "Finish" in str(caught.value.detail)
-
-
-def test_install_hint_pins_the_supported_release() -> None:
- """The card's install command must name the pinned release — a silent
- unpin would send users to a version the trust gate rejects."""
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
- assert spec.install_hint == "npm i -g @openai/[email protected]"
-
-
-def test_reason_code_vocabulary_is_pinned() -> None:
- """The five-layer enum contract: this list mirrors the TS union in
- useProviders.ts and the card mapping in ProviderTierSection.tsx — grow
- them together or the UI silently misrenders a new backend state."""
- from typing import get_args, get_type_hints
-
- from jarvis.codex_app_server import CodexAppServerCapability
-
- hints = get_type_hints(CodexAppServerCapability)
- assert set(get_args(hints["reason_code"])) == {
- "ready",
- "login_required",
- "login_in_progress",
- "lifecycle_unavailable",
- "not_installed",
- "setup_invalid",
- "plan_unsupported",
- "busy",
- }
-
-
-async def test_subscription_realtime_activation_preserves_realtime_mode(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis import codex_app_server
- from jarvis.core import config_writer
-
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": True,
- "mode": "chatgpt",
- "message": "ready",
- "reason_code": "ready",
- },
- )
-
- close_calls: list[object] = []
- release_calls: list[str] = []
-
- async def release_previous_transport() -> None:
- release_calls.append("released")
-
- class _Client:
- async def require_chatgpt_login(self) -> None:
- return None
-
- async def close(self) -> None:
- close_calls.append(self)
-
- monkeypatch.setattr(
- codex_app_server,
- "get_shared_codex_app_server",
- lambda *_args, **_kwargs: _Client(),
- )
- monkeypatch.setattr(
- codex_app_server,
- "set_codex_subscription_activation_block",
- lambda _value: None,
- )
- monkeypatch.setattr(
- routes,
- "_release_codex_transports_for_voice_switch",
- release_previous_transport,
- )
- persisted: list[tuple[str, str]] = []
- monkeypatch.setattr(
- config_writer,
- "set_realtime_provider",
- lambda provider: persisted.append(("provider", provider)),
- )
- config = SimpleNamespace(
- codex=SimpleNamespace(binary_path="codex"),
- voice=SimpleNamespace(profile="", mode="realtime"),
- brain=SimpleNamespace(realtime=None),
- )
- response = await routes.realtime_switch(
- routes.SwitchBody(
- provider="codex-subscription-realtime",
- persist=True,
- accept_experimental=True,
- ),
- SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=config))),
- )
-
- assert response["profile"] == ""
- assert response["mode"] == "realtime"
- assert config.voice.mode == "realtime"
- assert config.brain.realtime.provider == "codex-subscription-realtime"
- assert close_calls == []
- assert release_calls == ["released"]
- assert persisted == [("provider", "codex-subscription-realtime")]
-
-
-async def test_subscription_realtime_activation_repairs_the_old_pipeline_profile(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis import codex_app_server
- from jarvis.core import config_writer
-
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": True,
- "mode": "chatgpt",
- "message": "ready",
- "reason_code": "ready",
- },
- )
-
- class _Client:
- async def require_chatgpt_login(self) -> None:
- return None
-
- monkeypatch.setattr(
- codex_app_server,
- "get_shared_codex_app_server",
- lambda *_args, **_kwargs: _Client(),
- )
- monkeypatch.setattr(
- codex_app_server,
- "set_codex_subscription_activation_block",
- lambda _value: None,
- )
-
- async def release_previous_transport() -> None:
- return None
-
- monkeypatch.setattr(
- routes,
- "_release_codex_transports_for_voice_switch",
- release_previous_transport,
- )
-
- writes: list[tuple[str, str, str]] = []
- monkeypatch.setattr(
- config_writer,
- "set_realtime_voice_selection",
- lambda provider, *, profile, mode: writes.append(
- (provider, profile, mode)
- ),
- )
- config = SimpleNamespace(
- codex=SimpleNamespace(binary_path="codex"),
- voice=SimpleNamespace(profile="codex-subscription-voice", mode="pipeline"),
- brain=SimpleNamespace(realtime=SimpleNamespace(provider="openai-realtime")),
- )
-
- response = await routes.realtime_switch(
- routes.SwitchBody(
- provider="codex-subscription-realtime",
- persist=True,
- accept_experimental=True,
- ),
- SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=config))),
- )
-
- assert response["mode"] == "realtime"
- assert response["profile"] == ""
- assert config.voice.mode == "realtime"
- assert config.voice.profile == ""
- assert config.brain.realtime.provider == "codex-subscription-realtime"
- assert writes == [("codex-subscription-realtime", "", "realtime")]
-
-
-async def test_switching_away_releases_the_subscription_voice_transport(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- import jarvis.core.registry as registry
-
- spec = SimpleNamespace(
- id="replacement-realtime",
- tier="realtime",
- experimental=False,
- )
- release_calls: list[str] = []
-
- class Provider:
- requires_webrtc_offer = False
-
- @classmethod
- async def verify_activation(cls, _cfg: object) -> None:
- return None
-
- async def credential_present(*_args, **_kwargs) -> bool:
- return True
-
- async def release_previous_transport() -> None:
- release_calls.append("released")
-
- monkeypatch.setattr(routes, "get_spec", lambda _provider: spec)
- monkeypatch.setattr(
- routes,
- "_provider_credential_present_async",
- credential_present,
- )
- monkeypatch.setattr(registry, "load", lambda *_args, **_kwargs: Provider)
- monkeypatch.setattr(
- routes,
- "_release_codex_transports_for_voice_switch",
- release_previous_transport,
- )
- config = SimpleNamespace(
- voice=SimpleNamespace(
- profile="codex-subscription-voice",
- mode="pipeline",
- ),
- brain=SimpleNamespace(
- realtime=SimpleNamespace(provider="codex-subscription-realtime")
- ),
- )
-
- response = await routes.realtime_switch(
- routes.SwitchBody(provider=spec.id, persist=False),
- SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=config))),
- )
-
- assert response["active"] == spec.id
- assert release_calls == ["released"]
- assert config.voice.profile == ""
-
-
-async def test_voice_switch_release_closes_shared_codex_transports(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis import codex_app_server
-
- calls: list[str] = []
-
- async def close_shared() -> None:
- calls.append("closed")
-
- monkeypatch.setattr(
- codex_app_server,
- "close_shared_codex_app_servers",
- close_shared,
- )
-
- await routes._release_codex_transports_for_voice_switch()
-
- assert calls == ["closed"]
-
-
-async def test_realtime_activation_uses_provider_capability_not_provider_id(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- import jarvis.core.registry as registry
-
- config = SimpleNamespace(marker="active-config")
- request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=config)))
- spec = SimpleNamespace(
- id="arbitrary-subscription-transport",
- tier="realtime",
- experimental=False,
- )
- verified: list[object] = []
-
- class Provider:
- @classmethod
- async def verify_activation(cls, cfg: object) -> None:
- verified.append(cfg)
- raise RuntimeError("provider capability rejected activation")
-
- async def credential_present(*_args, **_kwargs) -> bool:
- return True
-
- monkeypatch.setattr(routes, "get_spec", lambda _provider: spec)
- monkeypatch.setattr(
- routes,
- "_provider_credential_present_async",
- credential_present,
- )
- monkeypatch.setattr(registry, "load", lambda *_args, **_kwargs: Provider)
-
- with pytest.raises(HTTPException) as caught:
- await routes.realtime_switch(
- routes.SwitchBody(
- provider=spec.id,
- persist=False,
- ),
- request,
- )
-
- assert caught.value.status_code == 409
- assert "capability rejected" in str(caught.value.detail)
- assert verified == [config]
-
-
-def _request_with_codex_path() -> SimpleNamespace:
- return SimpleNamespace(
- app=SimpleNamespace(
- state=SimpleNamespace(
- config=SimpleNamespace(codex=SimpleNamespace(binary_path="codex-custom"))
- )
- )
- )
-
-
-async def test_subscription_voice_status_uses_isolated_snapshot(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- expected = {
- "installed": True,
- "connected": True,
- "mode": "chatgpt",
- "message": "ready",
- }
- monkeypatch.setattr(
- routes,
- "_codex_subscription_status_payload",
- lambda binary_path: expected | {"binary_path": binary_path},
- )
-
- result = await routes.codex_subscription_voice_status(_request_with_codex_path())
-
- assert result["connected"] is True
- assert result["binary_path"] == "codex-custom"
-
-
- ("available", "authenticated", "version", "reason_code"),
- [
- (True, True, "codex-cli 0.146.0", "ready"),
- (True, False, "codex-cli 0.146.0", "login_required"),
- (False, False, "codex-cli 0.146.0", "login_required"),
- (False, False, None, "not_installed"),
- (False, False, "codex-cli 0.147.0", "setup_invalid"),
- (False, False, None, "busy"),
- ],
-)
-def test_subscription_status_has_stable_reason_codes(
- monkeypatch: pytest.MonkeyPatch,
- available: bool,
- authenticated: bool,
- version: str | None,
- reason_code: str,
-) -> None:
- from jarvis import codex_app_server
-
- snapshot = codex_app_server.CodexAppServerCapability(
- available=available,
- chatgpt_authenticated=authenticated,
- binary_path="codex" if version is not None else None,
- version=version,
- reason="setup result",
- reason_code=reason_code,
- )
- monkeypatch.setattr(
- codex_app_server,
- "codex_subscription_auth_snapshot",
- lambda _binary_path: snapshot,
- )
-
- payload = routes._codex_subscription_status_payload(None)
-
- assert payload["reason_code"] == reason_code
-
-
-async def test_subscription_voice_login_uses_dedicated_helper(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis import codex_app_server
-
- calls: list[str | None] = []
- monkeypatch.setattr(
- codex_app_server,
- "start_codex_subscription_login",
- lambda binary_path=None: calls.append(binary_path) or SimpleNamespace(pid=731),
- )
-
- result = await routes.codex_subscription_voice_login(_request_with_codex_path())
-
- assert calls == ["codex-custom"]
- assert result["pid"] == 731
-
-
-async def test_subscription_voice_logout_uses_atomic_backend_helper(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis import codex_app_server
-
- calls: list[str | None] = []
-
- async def disconnect_and_logout(binary_path=None):
- calls.append(binary_path)
- return True, None
-
- monkeypatch.setattr(
- codex_app_server,
- "disconnect_and_logout_codex_subscription",
- disconnect_and_logout,
- )
-
- result = await routes.codex_subscription_voice_logout(_request_with_codex_path())
-
- assert calls == ["codex-custom"]
- assert result["ok"] is True
-
-
-async def test_subscription_voice_logout_does_not_parse_exception_prose(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis import codex_app_server
-
- async def malformed_profile(_binary_path=None):
- raise codex_app_server.CodexSubscriptionUnavailable(
- "The profile has not been created but is also malformed."
- )
-
- monkeypatch.setattr(
- codex_app_server,
- "disconnect_and_logout_codex_subscription",
- malformed_profile,
- )
-
- with pytest.raises(HTTPException) as caught:
- await routes.codex_subscription_voice_logout(_request_with_codex_path())
-
- assert caught.value.status_code == 409
-
-
-def test_subscription_voice_logout_is_marked_dangerous_in_openapi() -> None:
- route = next(
- route
- for route in routes.router.routes
- if getattr(route, "path", None) == "/api/codex/subscription-voice/logout"
- )
-
- assert route.openapi_extra == {"x-jarvis-dangerous": True}
diff --git a/tests/unit/web/test_realtime_option_validation.py b/tests/unit/web/test_realtime_option_validation.py
index 662b6eacee..4d4b49fd4e 100644
--- a/tests/unit/web/test_realtime_option_validation.py
+++ b/tests/unit/web/test_realtime_option_validation.py
@@ -110,19 +110,12 @@ def test_get_realtime_options_reports_preview_capability(
api_response = client.get(
"/api/providers/openai-realtime/realtime-options"
)
- subscription_response = client.get(
+ removed_response = client.get(
"/api/providers/codex-subscription-realtime/realtime-options"
)
assert api_response.status_code == 200
assert api_response.json()["preview_available"] is True
- assert subscription_response.status_code == 200
- body = subscription_response.json()
- assert body["preview_available"] is True
- assert body["models"] == [
- {"id": "auto", "label": "ChatGPT-Live (model chosen by OpenAI)"}
- ]
- assert body["voices"][0] == {"id": "cove", "label": "cove"}
- assert "configured-tts" not in {voice["id"] for voice in body["voices"]}
- assert body["current_model"] == ""
- assert body["current_voice"] == ""
+ # The subscription realtime card was removed 2026-08-10; its options
+ # endpoint answers 404 like any other unknown provider id.
+ assert removed_response.status_code == 404
diff --git a/tests/unit/web/test_realtime_provider_category.py b/tests/unit/web/test_realtime_provider_category.py
index 800cb73991..4f9aedf05e 100644
--- a/tests/unit/web/test_realtime_provider_category.py
+++ b/tests/unit/web/test_realtime_provider_category.py
@@ -79,10 +79,9 @@ def test_list_providers_includes_active_realtime_provider(monkeypatch):
assert realtime["configured"] is True
-def test_list_providers_omits_hidden_codex_subscription_card(monkeypatch):
- """Withdrawn for v1.3.0: subscription voice over Codex's experimental
- Realtime protocol is not reliable enough to offer, so the catalog must
- not serve the card (and with it, the settings UI must not render one)."""
+def test_list_providers_omits_removed_codex_subscription_card(monkeypatch):
+ """The codex-subscription-realtime card was removed 2026-08-10 together
+ with its adapter; the catalog must not serve it."""
monkeypatch.setattr(cfg_mod, "get_secret", _only_openai_key)
client = TestClient(_app())
@@ -93,14 +92,10 @@ def test_list_providers_omits_hidden_codex_subscription_card(monkeypatch):
assert "codex-subscription-realtime" not in ids
-def test_hidden_spec_stays_resolvable_for_existing_selections():
- """``hidden`` is presentation-gating only (AP-21): the spec keeps
- resolving so an already-persisted selection and the explicit API/CLI
- switch path keep working exactly as before."""
- spec = get_spec("codex-subscription-realtime")
- assert spec is not None
- assert spec.hidden is True
- assert spec.tier == "realtime"
+def test_removed_subscription_realtime_spec_is_gone():
+ """The removed card's id must resolve to nothing anywhere — an existing
+ persisted selection is migrated at config load instead of resolving."""
+ assert get_spec("codex-subscription-realtime") is None
def test_list_providers_resolves_gemini_only_fresh_install(monkeypatch):
diff --git a/tests/unit/web/test_realtime_voice_preview.py b/tests/unit/web/test_realtime_voice_preview.py
index ccbe2a7110..b39245298e 100644
--- a/tests/unit/web/test_realtime_voice_preview.py
+++ b/tests/unit/web/test_realtime_voice_preview.py
@@ -43,7 +43,6 @@ def test_every_preview_sampler_has_a_cataloged_realtime_provider() -> None:
from jarvis.brain.model_catalog import REALTIME_VOICES
assert set(provider_routes._REALTIME_PREVIEW_SAMPLERS) <= set(REALTIME_VOICES)
- assert "codex-subscription-realtime" in provider_routes._REALTIME_PREVIEW_SAMPLERS
def test_unknown_provider_is_404() -> None:
@@ -87,9 +86,11 @@ def test_missing_credential_is_409(monkeypatch: pytest.MonkeyPatch) -> None:
assert "credentials" in response.json()["detail"]
-def test_subscription_preview_does_not_require_an_api_key(
+def test_keyless_preview_does_not_require_an_api_key(
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """``requires_api_key = False`` is a generic sampler capability: a keyless
+ provider's preview must not be blocked on a missing credential."""
monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _pid: None)
async def sampler(*_args, **_kwargs) -> tuple[bytes, int]:
@@ -98,14 +99,14 @@ def test_subscription_preview_does_not_require_an_api_key(
sampler.requires_api_key = False # type: ignore[attr-defined]
monkeypatch.setitem(
provider_routes._REALTIME_PREVIEW_SAMPLERS,
- "codex-subscription-realtime",
+ "local-realtime",
sampler,
)
response = _preview(
TestClient(_app()),
- "codex-subscription-realtime",
- voice="cove",
+ "local-realtime",
+ voice="auto",
)
assert response.status_code == 200
diff --git a/tests/unit/web/test_voice_mode_route.py b/tests/unit/web/test_voice_mode_route.py
index a830eb1ff1..7668d5d09a 100644
--- a/tests/unit/web/test_voice_mode_route.py
+++ b/tests/unit/web/test_voice_mode_route.py
@@ -13,7 +13,6 @@ from __future__ import annotations
from types import SimpleNamespace
-import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
@@ -21,20 +20,6 @@ from jarvis.browser_voice.route import _browser_voice_enabled
from jarvis.ui.web.settings_routes import router
[email protected](autouse=True)
-def _disable_machine_codex_subscription_login(monkeypatch):
- """Keep API-key route tests independent of the host's Codex login."""
- from jarvis.plugins.realtime.codex_subscription import (
- CodexSubscriptionRealtimeProvider,
- )
-
- monkeypatch.setattr(
- CodexSubscriptionRealtimeProvider,
- "external_login_ready",
- classmethod(lambda _cls: False),
- )
-
-
def test_gate_default_off_when_pipeline_and_no_browser_voice():
cfg = SimpleNamespace(voice=SimpleNamespace(mode="pipeline"))
assert _browser_voice_enabled(cfg) is False
@@ -97,7 +82,7 @@ def test_get_voice_mode_reports_browser_offer_capability(monkeypatch):
monkeypatch.setattr(
settings_routes,
"_realtime_available_provider",
- lambda _cfg: "codex-subscription-realtime",
+ lambda _cfg: "openai-realtime",
)
monkeypatch.setattr(
settings_routes,
@@ -116,9 +101,9 @@ def test_get_voice_mode_reports_browser_offer_capability(monkeypatch):
body = TestClient(_app(mode="realtime")).get("/api/settings/voice-mode").json()
- assert body["active_provider"] == "codex-subscription-realtime"
- assert body["active_model"] == "auto"
- assert body["active_model_label"] == "ChatGPT-Live (model chosen by OpenAI)"
+ assert body["active_provider"] == "openai-realtime"
+ assert body["active_model"] == "gpt-realtime"
+ assert body["active_model_label"] == "GPT Realtime (default)"
assert body["requires_webrtc_offer"] is True
assert body["transport_offer_ready"] is True
assert body["transport_offer_detail"] == "Embedded desktop WebRTC offer is ready."
@@ -214,91 +199,9 @@ def test_get_voice_mode_no_realtime_key_anywhere(monkeypatch):
assert body["active_model"] is None
-def test_put_voice_mode_codex_busy_answers_409_and_persists_nothing(monkeypatch):
- """The availability bool fails open on busy; the standing mode decision
- must not — it asks the payload and answers 'try again' instead."""
- from jarvis.ui.web import provider_routes, settings_routes
-
- monkeypatch.setattr(
- settings_routes,
- "_realtime_available_provider",
- lambda _cfg: "codex-subscription-realtime",
- )
- monkeypatch.setattr(
- provider_routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": "Dedicated subscription voice status is being checked or changed.",
- "reason_code": "busy",
- },
- )
- client = TestClient(_app(mode="pipeline"))
-
- r = client.put(
- "/api/settings/voice-mode", json={"mode": "realtime", "persist": True}
- )
-
- assert r.status_code == 409
- assert "being checked" in r.json()["detail"]
-
-
-def test_get_voice_mode_codex_busy_is_pending_not_ready(monkeypatch):
- """Status surfaces agree: busy means checking, never connected/ready."""
- from jarvis.ui.web import provider_routes, settings_routes
-
- monkeypatch.setattr(
- settings_routes,
- "_realtime_available_provider",
- lambda _cfg: "codex-subscription-realtime",
- )
- monkeypatch.setattr(
- provider_routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "connected": False,
- "reason_code": "busy",
- },
- )
-
- body = TestClient(_app(mode="realtime")).get(
- "/api/settings/voice-mode"
- ).json()
-
- assert body["active_provider"] == "codex-subscription-realtime"
- assert body["realtime_available"] is False
- assert body["realtime_availability_pending"] is True
-
-
-def test_put_voice_mode_codex_logged_out_is_400(monkeypatch):
- """A pinned but logged-out provider must not be persisted as the mode."""
- from jarvis.ui.web import provider_routes, settings_routes
-
- monkeypatch.setattr(
- settings_routes,
- "_realtime_available_provider",
- lambda _cfg: "codex-subscription-realtime",
- )
- monkeypatch.setattr(
- provider_routes,
- "_codex_subscription_status_payload",
- lambda _binary_path: {
- "installed": True,
- "connected": False,
- "mode": "not_connected",
- "message": "Connect the dedicated ChatGPT subscription voice login.",
- "reason_code": "login_required",
- },
- )
- client = TestClient(_app(mode="pipeline"))
-
- r = client.put(
- "/api/settings/voice-mode", json={"mode": "realtime", "persist": True}
- )
-
- assert r.status_code == 400
+# The codex-subscription-realtime adapter (and its busy/logged-out PUT gates)
+# was removed 2026-08-10; the generic "no ready provider" 400 below is the
+# remaining refusal path for an unavailable realtime engine.
def test_put_voice_mode_invalid_is_400():