Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions docs/refactoring/test-audit.md
Original file line number Diff line number Diff line change
@@ -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.
68 changes: 68 additions & 0 deletions docs/refactoring/untangle.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 0 additions & 3 deletions examples/chat/assets/js/audio.js
Original file line number Diff line number Diff line change
Expand Up @@ -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"); }
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions examples/chat/lib/chat/catalog.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
9 changes: 2 additions & 7 deletions examples/chat/lib/chat/engine.ex
Original file line number Diff line number Diff line change
@@ -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?(),
Expand All @@ -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
}
Expand Down
22 changes: 19 additions & 3 deletions examples/chat/lib/chat/setup.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand All @@ -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) ->
Expand All @@ -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
Expand Down
12 changes: 0 additions & 12 deletions examples/chat/lib/chat/wav.ex

This file was deleted.

30 changes: 11 additions & 19 deletions examples/chat/lib/chat_web/live/chat_live.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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])

Expand All @@ -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}
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -606,39 +606,31 @@ defmodule ChatWeb.ChatLive do
<form id="configuration" phx-submit="configure" class="flex flex-wrap gap-2">
<label>Pipeline
<select name="mode"><option
:for={
{id, label} <- [
{"demo", "Synthetic demo"},
{"local", "Local Apple MLX"},
{"remote", "Deepgram → Chat HTTP → TTS"},
{"openai", "OpenAI speech-to-speech"},
{"gemini", "Gemini speech-to-speech"}
]
}
:for={{id, label} <- Setup.modes()}
value={id}
selected={@settings["mode"] == id}
>
{label}
</option></select></label>
<label>Remote chain language
<select name="language"><option
:for={lang <- ~w(en es fr de ro)}
:for={lang <- Setup.languages()}
value={lang}
selected={@settings["language"] == lang}
>
{lang}
</option></select></label>
<label>Remote TTS
<select name="tts"><option
:for={tts <- ~w(elevenlabs cartesia)}
:for={tts <- Setup.tts_providers()}
value={tts}
selected={@settings["tts"] == tts}
>
{tts}
</option></select></label>
<label>OpenAI voice
<select name="voice"><option
:for={voice <- ~w(marin cedar)}
:for={voice <- Setup.voices()}
value={voice}
selected={@settings["voice"] == voice}
>
Expand Down
Loading
Loading