runtime: the session owner keeps a console --record recording in .livekit/sessions/

This commit is contained in:
Théo Monnom committed 2026-11-12 14:17:44 -08:00
1 parent 988bd6bddb
commit ea7d502b7d
8 files changed
+83 -33

No files matched your search

@@ -1013,6 +1013,11 @@ class _core_SessionOwner:
"""`aclose` without waiting for it."""
async def finish_recording(self) -> None:
"""The recording's final result remains available to the job reporter."""
async def keep_console_recording(self, report: SessionReport) -> str | None:
"""`console --record`: `report` and the call's audio are kept in
`.livekit/sessions/<local date-time>/` under the working directory, which is returned;
`None` for any other session. Call after `finish_recording`.
"""
@property
def started_at(self) -> float | None:
"""When the session started (wall clock seconds), once its startup prepared it."""
+7 -27
View File
@@ -16,13 +16,11 @@ from __future__ import annotations
import asyncio
import contextvars
import datetime
import functools
import inspect
import logging
import multiprocessing as mp
import os
import shutil
import tempfile
from collections.abc import Awaitable, Callable, Coroutine
from pathlib import Path
@@ -201,22 +199,13 @@ class JobContext:
logger.exception("failed to snapshot the session report")
return
from .voice._session_bindings import ConsoleCall
if ConsoleCall.record:
directory = Path(
".livekit", "sessions", datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
)
try:
await asyncio.to_thread(
_keep_console_recording,
self.make_session_report(),
self.session_directory,
directory,
)
logger.info(f"session recording saved to {directory.resolve()}")
except Exception:
logger.exception("failed to save the session recording")
try:
kept = await session._native.keep_console_recording(self.make_session_report())
except Exception:
logger.exception("failed to keep the session recording")
else:
if kept is not None:
logger.info(f"session recording saved to {Path(kept).resolve()}")
async def _on_cleanup(self) -> None:
await asyncio.to_thread(self._tempdir.cleanup)
@@ -705,12 +694,3 @@ class JobProcess:
@property
def http_proxy(self) -> str | None:
return self._http_proxy
def _keep_console_recording(report: SessionReport, session: Path, directory: Path) -> None:
"""`console --record`: the report and the call's audio outlive the job's temporary directory."""
directory.mkdir(parents=True, exist_ok=True)
(directory / "session_report.json").write_text(_core.session_report_json(report))
audio = session / "audio.ogg"
if audio.is_file():
shutil.copyfile(audio, directory / "audio.ogg")
@@ -15,7 +15,7 @@ from tests_new.fakes import FakeAudioInput, FakeSTT, FakeVAD, until
from .conftest import ConsolePeer
RECORDING_AGENT_MODULE = """
import asyncio, os, shutil
import asyncio
from livekit.agents import Agent, AgentServer, VoiceSession, cli
from tests_new.fakes import FakeTTS
@@ -29,7 +29,6 @@ async def entrypoint(ctx):
await session.say("hello there")
await asyncio.sleep(0.5) # the call lasts half a second
await session.aclose()
shutil.copy(ctx.session_directory / "audio.ogg", os.environ["RECORDING"])
ctx.shutdown()
if __name__ == "__main__":
@@ -70,9 +69,9 @@ async def test_a_recorded_console_call_writes_its_audio_without_a_room(
agent_env: dict[str, str],
tmp_path: Path,
) -> None:
"""``console --record`` records the call's audio although the console has no room.
https://github.com/livekit/agents/pull/4575"""
agent, recording = agent_module(RECORDING_AGENT_MODULE), tmp_path / "audio.ogg"
"""``console --record`` records the call's audio although the console has no room, and keeps
it with the report under ``.livekit/sessions/``. https://github.com/livekit/agents/pull/4575"""
agent = agent_module(RECORDING_AGENT_MODULE)
console_call = await asyncio.create_subprocess_exec(
sys.executable,
@@ -81,11 +80,14 @@ async def test_a_recorded_console_call_writes_its_audio_without_a_room(
"--record",
"--connect-addr",
console.addr,
env={**agent_env, "RECORDING": str(recording)},
env=agent_env,
cwd=tmp_path,
)
assert await console_call.wait() == 0
[kept] = list((tmp_path / ".livekit" / "sessions").iterdir())
assert (kept / "session_report.json").is_file()
recording = kept / "audio.ogg"
decoder = media.AudioStreamDecoder(format="audio/ogg")
decoder.push(recording.read_bytes())
decoder.end_input()