diff --git a/docs/refactoring/test-audit.md b/docs/refactoring/test-audit.md new file mode 100644 index 0000000..227ae2d --- /dev/null +++ b/docs/refactoring/test-audit.md @@ -0,0 +1,59 @@ +# Test review + +## Baseline + +The first full core run had 15 failures. Each failure occurred before the +recording behavior ran: `Store.new/1` returned `{:error, :unsafe_path}`. +The setup used `System.tmp_dir!/0`. On macOS this path can contain a symlink. +The store rejects symlinks in all path segments. This is its security contract. + +## Changes + +- Repair temporary directory setup in `recording_test.exs`, + `recording_runtime_test.exs`, `cross_feature_acceptance_test.exs`, and + `remote_providers_test.exs`. Use ExUnit's `:tmp_dir` context. It gives each test + a directory under the project `tmp/` path. Keep all persistence, privacy, + retention, lifecycle, permission, and symlink checks. +- In `input_processing_test.exs`, remove checks of `speaking?`, + `semantic_checked_at`, and `reference_pending`. The returned events and PCM + check the behavior. Check the exact utterance and detector input on both + semantic completion cycles. A reset failure must prevent the second cycle + from completing and thus fail the test. +- In `graph_checkpoint_test.exs`, use the audio fixture duration for playback + acknowledgements. Do not read the session's private playout state. Branches + emit four two-sample chunks at 16 kHz: 500,000 ns. A joined node emits no + audio while its source is blocked. Silent and partial cases each emit one + two-sample chunk: 125,000 ns. +- In `conversation_test.exs`, let the controlled adapter send its task PID to + the test. Resume and failure commands go to that fixture PID. The tests no + longer read the session's private `active.task.pid` fields. The checks still + prove successful handoff, stale tool rejection, and rollback after failure. + +No test was deleted. The reviewed negative recording checks protect current +privacy, persistence, or path security requirements. Graph catalog checks +protect public metadata. Codec reference values and dependency compatibility +checks have independent contracts. Similar tests at session and transport +levels protect different lifecycle behavior. + +## Evidence + +The recording owner and store, all four repaired test files, their recent +history, CI routing, input processing, voice input, graph checkpoint, playout, +conversation, graph options, retrieval, and telephony tests were read. +The test tree was searched for source checks, constant assertions, private +state access, and skip tags. No deletion candidate had enough evidence to +remove its contract. + +The fixture changes add no production code or test-only production interface. +The store security rules are unchanged. + +## Checks + +- Recording and provider tests: 25 passed. +- Input processing and graph checkpoint tests: 8 passed. +- Conversation tests: 5 passed. +- Focused tests require local TCP access for the Mix build lock. Provider tests + also use local sockets. +- Final core and avatar server suite: 224 passed, 3 skipped, 5 excluded. +- UI: 28 passed. Chat: 12 passed. WebRTC: 12 passed. +- Final independent review found no further issue worth fixing. diff --git a/docs/refactoring/untangle.md b/docs/refactoring/untangle.md new file mode 100644 index 0000000..a202c3e --- /dev/null +++ b/docs/refactoring/untangle.md @@ -0,0 +1,68 @@ +# Code structure decisions + +Scope: the core library, optional libraries, UI, examples, scripts, and documentation. +The initial working tree was clean. The user selected comment and test cleanup. Remove implementation comments and review tests after structural changes. + +## Problems and changes + +- Put session connection state and domain events in a shared transport module. Keep JSON encoding in each WebSocket endpoint. + - RTVI and telephony call the raw PCM WebSocket handler and decode its JSON to recover events. + - RTVI encodes commands to JSON to call the raw PCM handler. + - Telephony intercepts private PCM output messages to enforce its output limits. +- Put PCMU conversion and packet completion in one packetizer. + - Telephony and WebRTC copy the rate conversion, 160-byte packets, filter tail, and silence padding. +- Let adapters merge execution context through an optional adapter callback. + - The graph runner names ReqLLM and ChatHTTP and knows their option layouts. +- Put linear PCM conversion in the resampler module, and retain its existing algorithm. + - The graph node module owns a general audio conversion algorithm. Other callers must import graph code to use it. +- Use the core WAV encoder in the UI and chat application. + - Three modules copy the same WAV header construction. +- Record the chat build profile in application configuration. + - Build configuration and runtime code independently select native mode from the environment. +- Keep chat choices and defaults with their owners. + - Chat setup validation and LiveView markup copy the mode, language, voice, and TTS choices. + - The demo engine and native engine copy model and voice defaults. +- Let graph node families report configuration requirements. + - UI prerequisite checks inspect the provider registry and name the RAG node and its configuration. +- Build the UI conversation example through a node catalog. + - The example edits nested compiled conversation plans to replace adapters. +- Store each graph node family and the model adapter in its own file. + - `graph/nodes.ex` contains four unrelated families; `graph/models.ex` contains a second module. + +## Cases to retain + +- PCM conversion algorithms serve different contracts: complete audio uses a sinc filter; graph linear conversion keeps its existing output; streaming telephony keeps filter state. +- Provider protocol differences, credential checks, frame bounds, reorder deadlines, playback pacing, stale message checks, and optional dependency profiles are current requirements. +- Model, distributed-node, and native pipeline tests need external resources. Their opt-in tags are required. +- Adapter and transport exception conversion keeps failures inside the documented error contract. +- Site documentation and repository guides have different navigation and context. Similar text alone does not justify removing either published entry point. + +## Verification + +- Initial `mix test` could not start because dependencies were absent. Locked dependencies were then installed. +- Full core and avatar server suite: 224 passed, 3 skipped, 5 excluded. +- UI suite: 28 passed. Chat suite: 12 passed. +- WebRTC suites: 12 passed. Core transport checks: 25 passed. +- Browser audio checks: 4 passed. Python report checks: 5 passed. +- Core type checks, changed-code lint, formatting, and whitespace checks passed. +- Native WebRTC first failed before media handling. The downloaded SRTP library + could not find OpenSSL 3. A link in the ignored native build cache repaired + the local library path. No dependency source or lockfile changed. +- Native model inference and hardware media tests remain opt-in. No model + weights or device sessions were started for this refactor. + +## Final review + +Independent agents checked graph execution, audio conversion, application +settings, transport events, packet completion, and test value. All accepted +findings are resolved. No further structural issue worth fixing was found in +those reviews. + +The review removed unused legacy WebSocket message forwarding. Public output +callbacks still work. Tests now use current transport messages. The filter +owns its own completion length, so the packetizer does not copy that constant. +The workflow graph names its reply type without relying on node order. + +The test review is recorded in [test-audit.md](test-audit.md). No tests were +deleted. Tests use observable events and audio where private state was not +needed. Required protocol and resource limits remain in place. diff --git a/examples/chat/assets/js/audio.js b/examples/chat/assets/js/audio.js index 54f5a63..0b0b79d 100644 --- a/examples/chat/assets/js/audio.js +++ b/examples/chat/assets/js/audio.js @@ -83,7 +83,6 @@ export const Recorder = { window.dispatchEvent(new CustomEvent("chat:flush")); try { - // Load the worklet while the browser opens the microphone. const context = new AudioContext(); this.targetRate = Number(this.el.dataset.rate || INPUT_RATE); if (context.sampleRate < this.targetRate) { await context.close(); throw new Error("Capture sample rate is below required PCM rate"); } @@ -111,7 +110,6 @@ export const Recorder = { } }, - // Conversion is deterministic per sample, so earlier samples do not change. send(event) { const capture = this.capture; if (!capture) return; @@ -199,7 +197,6 @@ export const Player = { this.handleEvent("output_control", (command) => { const epoch = this.epoch; - // Serialize actual Web Audio operations. A resume never overtakes suspend. this.commands = this.commands.then(async () => { if (epoch !== this.epoch || command.token !== this.token) return; try { diff --git a/examples/chat/lib/chat/catalog.ex b/examples/chat/lib/chat/catalog.ex index b5c166b..b549638 100644 --- a/examples/chat/lib/chat/catalog.ex +++ b/examples/chat/lib/chat/catalog.ex @@ -7,6 +7,10 @@ defmodule Chat.Catalog do about twice its f16 download. Compiled kernels and caches add to this. """ + @defaults %{stt: "whisper-small", llm: "qwen3-1.7b", voice: "af_heart"} + + def defaults, do: @defaults + @stt [ %{ id: "whisper-tiny", diff --git a/examples/chat/lib/chat/engine.ex b/examples/chat/lib/chat/engine.ex index 1e62149..88f90b0 100644 --- a/examples/chat/lib/chat/engine.ex +++ b/examples/chat/lib/chat/engine.ex @@ -1,12 +1,7 @@ defmodule Chat.Engine do @moduledoc "Profile boundary: only native builds start model processes." @compile {:no_warn_undefined, Chat.LocalEngine} - def native?, - do: - System.get_env( - "CHAT_PROFILE", - if(:os.type() == {:unix, :darwin}, do: "native", else: "demo") - ) == "native" + def native?, do: Application.fetch_env!(:chat, :native_profile) def child_spec(_) do if native?(), @@ -25,7 +20,7 @@ defmodule Chat.Engine do if native?(), do: Chat.LocalEngine.status(), else: %{ - selection: %{stt: "whisper-small", llm: "qwen3-1.7b", voice: "af_heart"}, + selection: Chat.Catalog.defaults(), status: %{}, memory_gb: 0 } diff --git a/examples/chat/lib/chat/setup.ex b/examples/chat/lib/chat/setup.ex index 7b4b634..d740a7e 100644 --- a/examples/chat/lib/chat/setup.ex +++ b/examples/chat/lib/chat/setup.ex @@ -2,6 +2,22 @@ defmodule Chat.Setup do @moduledoc "Validated per-tab settings. Credentials are resolved only on the server." alias AudioFlow.Adapters + @modes [ + {"demo", "Synthetic demo"}, + {"local", "Local Apple MLX"}, + {"remote", "Deepgram → Chat HTTP → TTS"}, + {"openai", "OpenAI speech-to-speech"}, + {"gemini", "Gemini speech-to-speech"} + ] + @languages ~w(en es fr de ro) + @voices ~w(marin cedar) + @tts_providers ~w(elevenlabs cartesia) + + def modes, do: @modes + def languages, do: @languages + def voices, do: @voices + def tts_providers, do: @tts_providers + def defaults, do: %{ "mode" => if(Chat.Engine.native?(), do: "local", else: "demo"), @@ -23,7 +39,7 @@ defmodule Chat.Setup do missing = Enum.filter(required(s), &(env.(&1) in [nil, ""])) cond do - mode not in ["local", "demo", "remote", "openai", "gemini"] -> + not Enum.any?(@modes, &(elem(&1, 0) == mode)) -> {:error, "Unknown mode"} not supported?(s) -> @@ -50,8 +66,8 @@ defmodule Chat.Setup do defp required(s), do: requirements(s["mode"]) defp supported?(s) do - s["language"] in ["en", "es", "fr", "de", "ro"] and s["voice"] in ["marin", "cedar"] and - s["tts"] in ["elevenlabs", "cartesia"] + s["language"] in @languages and s["voice"] in @voices and + s["tts"] in @tts_providers end defp key(env, name), do: fn -> env.(name) end diff --git a/examples/chat/lib/chat/wav.ex b/examples/chat/lib/chat/wav.ex deleted file mode 100644 index b3139f8..0000000 --- a/examples/chat/lib/chat/wav.ex +++ /dev/null @@ -1,12 +0,0 @@ -defmodule Chat.Wav do - @moduledoc "Wraps mono s16le PCM in a WAV header for the browser audio player." - - def encode(pcm, rate) do - data = IO.iodata_to_binary(pcm) - size = byte_size(data) - - <<"RIFF", size + 36::little-32, "WAVE", "fmt ", 16::little-32, 1::little-16, 1::little-16, - rate::little-32, rate * 2::little-32, 2::little-16, 16::little-16, "data", size::little-32, - data::binary>> - end -end diff --git a/examples/chat/lib/chat_web/live/chat_live.ex b/examples/chat/lib/chat_web/live/chat_live.ex index 0ac90ab..f6dcdf3 100644 --- a/examples/chat/lib/chat_web/live/chat_live.ex +++ b/examples/chat/lib/chat_web/live/chat_live.ex @@ -16,7 +16,6 @@ defmodule ChatWeb.ChatLive do alias AudioFlow.Text alias Chat.Catalog alias Chat.Setup - alias Chat.Wav alias ChatWeb.Components.UI.Badge alias ChatWeb.Components.UI.Button alias ChatWeb.Components.UI.NativeSelect @@ -82,7 +81,6 @@ defmodule ChatWeb.ChatLive do end end - # A new recording interrupts the current reply. def handle_event("recording", _params, socket) do socket = cancel(socket) |> add_message("user", "", pending: true, live: true) id = List.last(socket.assigns.messages).id @@ -336,7 +334,6 @@ defmodule ChatWeb.ChatLive do def handle_info({AudioFlow, _, _, _}, socket), do: {:noreply, socket} def handle_info({:models, models}, socket), do: {:noreply, assign(socket, models: models)} - # A partial transcription finished. def handle_info({ref, result}, %{assigns: %{recording: %{task: ref} = recording}} = socket) do Process.demonitor(ref, [:flush]) @@ -355,7 +352,6 @@ defmodule ChatWeb.ChatLive do ), do: {:noreply, assign(socket, recording: %{r | task: nil})} - # Results of partial transcriptions for a recording that already ended. def handle_info({ref, _}, socket) when is_reference(ref) do Process.demonitor(ref, [:flush]) {:noreply, socket} @@ -404,7 +400,13 @@ defmodule ChatWeb.ChatLive do if socket.assigns.rate, do: %{ media_type: "audio/wav", - base64: Base.encode64(Wav.encode(socket.assigns.pcm, socket.assigns.rate)) + base64: + Base.encode64( + AudioFlow.Wav.encode(%AudioFlow.Audio{ + data: IO.iodata_to_binary(socket.assigns.pcm), + sample_rate: socket.assigns.rate + }) + ) } note = @@ -479,7 +481,6 @@ defmodule ChatWeb.ChatLive do ) end - # One partial transcription runs at a time, over the complete recording so far. defp maybe_transcribe(%{assigns: %{recording: %{invalid: true}}} = socket), do: socket defp maybe_transcribe(%{assigns: %{settings: %{"mode" => mode}}} = socket) when mode != "local", @@ -543,7 +544,6 @@ defmodule ChatWeb.ChatLive do assign(socket, messages: messages) end - # The newest user message that is not the live recording. defp update_last(socket, role, fun) do live = socket.assigns.recording && socket.assigns.recording.id @@ -606,15 +606,7 @@ defmodule ChatWeb.ChatLive do