From 87f418a1515d3f69fc6cbe192381d2857fd9c3d1 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 22:33:42 +0200 Subject: [PATCH 01/12] build(chat): separate build paths per profile and lock media deps AUDIOFLOW_MEDIA=1 adds the Membrane dependencies that AudioFlow.Duplex.Moshi needs. Each profile now compiles to its own build path, so a profile change does not reuse stale modules. --- examples/chat/mix.exs | 11 +++++++++++ examples/chat/mix.lock | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/examples/chat/mix.exs b/examples/chat/mix.exs index ca1290a..18ff18a 100644 --- a/examples/chat/mix.exs +++ b/examples/chat/mix.exs @@ -7,6 +7,16 @@ System.put_env("AUDIOFLOW_ML", if(native?, do: "1", else: "0")) defmodule Chat.MixProject do use Mix.Project @native_profile System.get_env("AUDIOFLOW_ML") == "1" + # AUDIOFLOW_MEDIA=1 compiles AudioFlow's media modules (Duplex, Moshi) into the + # dependency. Each profile has its own build path, so a profile change never + # reuses modules compiled for another profile. Native keeps the default path. + @media_profile System.get_env("AUDIOFLOW_MEDIA") == "1" + @build_path (case {@native_profile, @media_profile} do + {true, false} -> "_build" + {true, true} -> "_build/native_media" + {false, true} -> "_build/demo_media" + {false, false} -> "_build/demo" + end) # Set LIVE_SHADCN_PATH to a live_shadcn checkout to use local packages. @live_shadcn "3ddada48f623d72260360acf115e5d9b5eacd1cf" @@ -17,6 +27,7 @@ defmodule Chat.MixProject do app: :chat, version: "0.1.0", elixir: "~> 1.18", + build_path: @build_path, listeners: [Phoenix.CodeReloader], elixirc_paths: ["lib"] ++ if(@native_profile, do: ["native"], else: []), deps: deps(), diff --git a/examples/chat/mix.lock b/examples/chat/mix.lock index 13e0ca1..ed1039f 100644 --- a/examples/chat/mix.lock +++ b/examples/chat/mix.lock @@ -2,15 +2,22 @@ "abnf_parsec": {:hex, :abnf_parsec, "2.1.0", "c4e88d5d089f1698297c0daced12be1fb404e6e577ecf261313ebba5477941f9", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "e0ed6290c7cc7e5020c006d1003520390c9bdd20f7c3f776bd49bfe3c5cd362a"}, "axon": {:hex, :axon, "0.9.0", "882be41d4d5c8f6d9b09682147ddac186324b927beb3aa5c17536f6684a76753", [:mix], [{:kino, "~> 0.19", [hex: :kino, repo: "hexpm", optional: true]}, {:kino_vega_lite, "~> 0.1.7", [hex: :kino_vega_lite, repo: "hexpm", optional: true]}, {:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}, {:polaris, "~> 0.2", [hex: :polaris, repo: "hexpm", optional: false]}, {:table_rex, "~> 3.1 or ~> 4.1", [hex: :table_rex, repo: "hexpm", optional: true]}], "hexpm", "243611436749007a5ec5ec0f5ebe0eb2261d8999217a5fad068c46a51a0d649f"}, "bandit": {:hex, :bandit, "1.14.1", "5fb450e2360faf03d9b9fb45cfe52e14197f62d376c34781219bec0f9bc7ca06", [:mix], [{:hpax, "~> 1.1", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.18", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.6", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "87c7ee5e08fb5f22d4e072e681e1101266a21432889b08ef8d0cb0c1450f8bba"}, + "bimap": {:hex, :bimap, "1.3.0", "3ea4832e58dc83a9b5b407c6731e7bae87458aa618e6d11d8e12114a17afa4b3", [:mix], [], "hexpm", "bf5a2b078528465aa705f405a5c638becd63e41d280ada41e0f77e6d255a10b4"}, "bumblebee": {:hex, :bumblebee, "0.8.0", "24d44c902baf91cf91d7ac0eba1c0feb02590eca34892fc859022a3b6b604732", [:mix], [{:axon, "~> 0.9.0", [hex: :axon, repo: "hexpm", optional: false]}, {:jason, "~> 1.4.0", [hex: :jason, repo: "hexpm", optional: false]}, {:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}, {:nx_image, "~> 0.2.0", [hex: :nx_image, repo: "hexpm", optional: false]}, {:nx_signal, "~> 0.4.0", [hex: :nx_signal, repo: "hexpm", optional: false]}, {:safetensors, "~> 0.2.0", [hex: :safetensors, repo: "hexpm", optional: false]}, {:tokenizers, "~> 0.4", [hex: :tokenizers, repo: "hexpm", optional: false]}, {:unpickler, "~> 0.1.0", [hex: :unpickler, repo: "hexpm", optional: false]}, {:unzip, "~> 0.12.0 or ~> 0.13.0", [hex: :unzip, repo: "hexpm", optional: false]}], "hexpm", "283272b12c24a8ec8d3fc31c3564a39babeeff09e51670039090ee17014d59a6"}, + "bunch": {:hex, :bunch, "1.6.4", "b23ecefdcbc1d8b9723044055daa2ad8573a0ebe6ef35c0ac4f3bad243273ba3", [:mix], [], "hexpm", "cacbe7437dd5299c9e665011d32127e0ce92b26ab4b9f64ebd2389f57cc7c141"}, + "bunch_native": {:hex, :bunch_native, "0.5.2", "706723acd1644fb6f8e7c8f3864172a7eee7664250e790696253825e3b65e18a", [:mix], [{:bundlex, "~> 1.0", [hex: :bundlex, repo: "hexpm", optional: false]}], "hexpm", "23f9e036c34510d8ace14fc47553fd7672e2330e769ab84fe4b54fac80095a4b"}, + "bundlex": {:hex, :bundlex, "1.5.9", "8f4c85e7a8ecea275f71970a917172e6beb7cd241963ef302391ded8f6e2b146", [:mix], [{:bunch, "~> 1.0", [hex: :bunch, repo: "hexpm", optional: false]}, {:elixir_uuid, "~> 1.2", [hex: :elixir_uuid, repo: "hexpm", optional: false]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:qex, "~> 0.5", [hex: :qex, repo: "hexpm", optional: false]}, {:req, ">= 0.4.0", [hex: :req, repo: "hexpm", optional: false]}, {:zarex, "~> 1.0", [hex: :zarex, repo: "hexpm", optional: false]}], "hexpm", "ee2cd62e26a0470766f728a7903a74228059fcb54acd2e6d54a5e7b06ab1146d"}, "castore": {:hex, :castore, "1.0.22", "a01978e6a5d42fa3a34143630588f92036e7d90e2309ecdd466722d1279a2213", [:mix], [], "hexpm", "c2a4d42723b4affbc1c3e15d8f6df3f7d8f1f627c84de643383634cce58493d5"}, "cc_precompiler": {:hex, :cc_precompiler, "0.1.11", "8c844d0b9fb98a3edea067f94f616b3f6b29b959b6b3bf25fee94ffe34364768", [:mix], [{:elixir_make, "~> 0.7", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "3427232caf0835f94680e5bcf082408a70b48ad68a5f5c0b02a3bea9f3a075b9"}, + "coerce": {:hex, :coerce, "1.0.2", "5ef791040c92baaa5dd344887563faaeac6e6742573a167493294f8af3672bbe", [:mix], [], "hexpm", "0b3451c729571234fdac478636c298e71d1f2ce1243abed5fa43fa3181b980eb"}, "complex": {:hex, :complex, "1.0.0", "32075df521760e83d808652f52dd57f21712d47d5918a328709da78358387507", [:mix], [], "hexpm", "b4fd7ab305712472521043aa4322f7e4cdd85ca3ddf79c9c2c338d6663adc8d8"}, + "crc": {:hex, :crc, "0.11.0", "179cd2cb8d5f35d8b7d285eb12541da4680eefba253a5b97d4a949f7a30b56b4", [:mix, :rebar3], [], "hexpm", "b9e37d3e54c2d828611ad83dc2e0ea448c37cdb60a8b481355f9f68d69c9c3fc"}, "crontab": {:hex, :crontab, "1.2.1", "17991605725002e8dd949b95c1460b757b0702c048a7c9ea8b03183d08d3b9a9", [:mix], [{:ecto, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :ecto, repo: "hexpm", optional: true]}], "hexpm", "ab550a005380d30c05038a1abff66989591e7703b2cc0d83f446a86fab258150"}, "db_connection": {:hex, :db_connection, "2.10.2", "ae391e803a5adff104da913c2fc1c0c14a37f8b10001dcef568796e1fb7bf95c", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "510b14482330f1af6490a2fa0efd8d4f1435d1529b165647df22ac0f2df0fa93"}, "decimal": {:hex, :decimal, "3.2.0", "f1235f05d841a211fda78a08fdb9777f2ff51a71f18455233fae186ff76187c6", [:mix], [], "hexpm", "190bca80580ce61aa69bb0eacadd7677710205c770225c2c2c07e32a5c31b234"}, "dotenvy": {:hex, :dotenvy, "1.2.1", "43b28d17c996d70ac09f6a6dfd2245378b346ed7290c36452b46cdca77cd96bc", [:mix], [], "hexpm", "20cf780119be89a7cae7808543ebc8b7e56f0993b6aa058260fab686afe9073d"}, "elixir_make": {:hex, :elixir_make, "0.10.1", "f5a44ab6b48421de1c4fd33c147e22cd2f82fd86e8a9a4d24809d466cad63c5e", [:mix], [], "hexpm", "ce1eaa234bc87f0279718e793fd6f8ad35b4e8ee8d412329e3879eee8d40adba"}, + "elixir_uuid": {:hex, :elixir_uuid, "1.2.1", "dce506597acb7e6b0daeaff52ff6a9043f5919a4c3315abb4143f0b00378c097", [:mix], [], "hexpm", "f7eba2ea6c3555cea09706492716b0d87397b88946e6380898c2889d68585752"}, "emlx": {:git, "https://github.com/elixir-nx/emlx.git", "5f5cd886fd2550b1e9452ddc3943fec5597b0cd5", [ref: "5f5cd886fd2550b1e9452ddc3943fec5597b0cd5", sparse: "emlx"]}, "emlx_axon": {:git, "https://github.com/elixir-nx/emlx.git", "5f5cd886fd2550b1e9452ddc3943fec5597b0cd5", [ref: "5f5cd886fd2550b1e9452ddc3943fec5597b0cd5", sparse: "emlx_axon"]}, "exla": {:hex, :exla, "1.0.0", "1c24b1e38416c954bf45851e7591e945876b76ac37e6ba992f01bb72ea615163", [:make, :mix], [{:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}, {:fine, "~> 0.1", [hex: :fine, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.0", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:xla, "~> 0.10.0", [hex: :xla, repo: "hexpm", optional: false]}], "hexpm", "f89b030d368372fe62aacecc773e2d096d812d1afe55acfed333ac9a43864ba7"}, @@ -18,6 +25,7 @@ "finch": {:hex, :finch, "0.24.0", "4022b6194e907b6d9b597c168001cac38e488a35fe36cef9d8297e3159782510", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "33ba40069c3587c2f99f9125b766e19dad87d6d54be3c6961db2304df04cef00"}, "fine": {:hex, :fine, "0.1.6", "4bf7151493443c454aac9f2fa2f34f5fefd0346a83fb5586a016c4a135c63247", [:mix], [], "hexpm", "5638eb4495488e885ebec167fa57973e5c35e1a50c344eb7666c90ec1c4e3b12"}, "fuse": {:hex, :fuse, "2.5.0", "71afa90be21da4e64f94abba9d36472faa2d799c67fedc3bd1752a88ea4c4753", [:rebar3], [], "hexpm", "7f52a1c84571731ad3c91d569e03131cc220ebaa7e2a11034405f0bac46a4fef"}, + "heap": {:hex, :heap, "2.0.2", "d98cb178286cfeb5edbcf17785e2d20af73ca57b5a2cf4af584118afbcf917eb", [:mix], [], "hexpm", "ba9ea2fe99eb4bcbd9a8a28eaf71cbcac449ca1d8e71731596aace9028c9d429"}, "hf_hub": {:hex, :hf_hub, "0.3.1", "c3285b8c94b8622b9df137330a8a889c4f0ce171d459f9bc53e5d758a4dfcbcf", [:mix], [{:explorer, "~> 0.10", [hex: :explorer, repo: "hexpm", optional: true]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:req, "~> 0.5", [hex: :req, repo: "hexpm", optional: false]}, {:yaml_elixir, "~> 2.9", [hex: :yaml_elixir, repo: "hexpm", optional: false]}], "hexpm", "ad58acabb774fb89a34590b6995b0472f3343ffa27c3624a833f9374543169d1"}, "hpax": {:hex, :hpax, "1.1.0", "782931867cc23217c68fb5f68fe1a11f5e7544c7fda82c8a7019a5df5a4a1cdf", [:mix], [], "hexpm", "0b8d0f05832f55571d65ac720f79bf8994138ffbb133209dc4685eae0ad456a8"}, "idna": {:hex, :idna, "7.1.0", "1067a13043538129602d2f2ce6899d8713125c7d19734aa557ce2e3ea55bd4f1", [:rebar3], [], "hexpm", "6ae959a025bf36df61a8cab8508d9654891b5426a84c44d82deaffd6ddf8c71f"}, @@ -31,14 +39,39 @@ "live_base": {:git, "https://github.com/TudorAndrei/live_shadcn.git", "3ddada48f623d72260360acf115e5d9b5eacd1cf", [ref: "3ddada48f623d72260360acf115e5d9b5eacd1cf", sparse: "packages/live_base"]}, "live_shadcn": {:git, "https://github.com/TudorAndrei/live_shadcn.git", "3ddada48f623d72260360acf115e5d9b5eacd1cf", [ref: "3ddada48f623d72260360acf115e5d9b5eacd1cf", sparse: "packages/live_shadcn"]}, "llm_db": {:hex, :llm_db, "2026.10.7", "7a8a1ef710727a4b0314055c72cbfc7fa10de61ff8728a8189f1e896b410bd0e", [:mix], [{:dotenvy, "~> 1.1", [hex: :dotenvy, repo: "hexpm", optional: false]}, {:igniter, "~> 0.7", [hex: :igniter, repo: "hexpm", optional: true]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:req, "~> 0.5", [hex: :req, repo: "hexpm", optional: false]}, {:toml, "~> 0.7", [hex: :toml, repo: "hexpm", optional: false]}, {:zoi, "~> 0.18.11", [hex: :zoi, repo: "hexpm", optional: false]}], "hexpm", "eb4aa0a64ce3c4d80bd49a2e87ba830f5d2b2bed46fe5e2fc0e4ee0eb17c04bb"}, + "logger_backends": {:hex, :logger_backends, "1.0.1", "08a9bd09eed271eac41ff35dd7603b6abf9e0f8b6ffe40359846cb0bfd37704f", [:mix], [], "hexpm", "d7903244fe8d84eeb3d3d42f8d7de080fd0409b613040df54c78b3591672d652"}, "lucide_icons": {:hex, :lucide_icons, "2.4.7", "124c3998924a626a16f10569473530bc1008aabbdc2f5a327c7f64ae20b5ec34", [:mix], [{:phoenix_html, "~> 4.3", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 1.2", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}], "hexpm", "0f6de8ab224304c1b61c77e699d574bdd05bc68cd8390c7d42000831ef245ec9"}, + "membrane_aac_format": {:hex, :membrane_aac_format, "0.8.1", "1084337ac856fb59ef484f8e52a286d036142c1d025728bb47a6dfc868b91ddc", [:mix], [{:bimap, "~> 1.1", [hex: :bimap, repo: "hexpm", optional: false]}], "hexpm", "7e8fbaae4895947394bfafaa4ec823d7eea035a3ccfbfe57a534b2872bf92862"}, + "membrane_av1_format": {:hex, :membrane_av1_format, "0.3.1", "d7d52d11ef359f723f443a12836624ab19235353732f18e8b0adf23b1d1a5062", [:mix], [{:bimap, "~> 1.3", [hex: :bimap, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}], "hexpm", "dcea3c1f255a28d188e85a68a8729b258a3fb1a151254266a872000254f85b90"}, + "membrane_cmaf_format": {:hex, :membrane_cmaf_format, "0.7.2", "fe1aeb7705d4422329eb19039d30ddb7973fe62c06ea03ea6669dbd94bf7f380", [:mix], [], "hexpm", "91f2c07bfbadee69b46de6a568a91ac80c1a4eada82aa82957f003bad07bdfab"}, + "membrane_common_c": {:hex, :membrane_common_c, "0.16.2", "76272743921844cfcad9e97aec6ae00e349c679919e87ff8ea2131939b4838e4", [:mix], [{:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:shmex, "~> 0.5.0", [hex: :shmex, repo: "hexpm", optional: false]}, {:unifex, "~> 1.0", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "8416f95bdaeb147072be48418bbccab60e7f58bdbe24927be3a6903d96fea8be"}, + "membrane_core": {:hex, :membrane_core, "1.3.5", "10825d9359dcb440892a731528a11d8d7d704ee1607def41cc259c688f69a452", [:mix], [{:bunch, "~> 1.6", [hex: :bunch, repo: "hexpm", optional: false]}, {:qex, "~> 0.3", [hex: :qex, repo: "hexpm", optional: false]}, {:ratio, "~> 3.0 or ~> 4.0", [hex: :ratio, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "cec2027446d7fcc860289907ea7259e0385b468e795c635334cb80d3c5f2a366"}, + "membrane_ffmpeg_swresample_plugin": {:hex, :membrane_ffmpeg_swresample_plugin, "0.21.0", "30f9dc3b6bee6d62f3d7d85603ad3f18ca14ea52adfad88771b009a645a10eea", [:mix], [{:bunch, "~> 1.6", [hex: :bunch, repo: "hexpm", optional: false]}, {:bundlex, "~> 1.2", [hex: :bundlex, repo: "hexpm", optional: false]}, {:membrane_common_c, "~> 0.16.0", [hex: :membrane_common_c, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_precompiled_dependency_provider, "~> 0.2.1", [hex: :membrane_precompiled_dependency_provider, repo: "hexpm", optional: false]}, {:membrane_raw_audio_format, "~> 0.12.0", [hex: :membrane_raw_audio_format, repo: "hexpm", optional: false]}, {:mockery, "~> 2.1", [hex: :mockery, repo: "hexpm", optional: false]}, {:unifex, "~> 1.1", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "255177b22e39c7d20f1acceef8dda9fe7fd9094c5d906ffb0be4d6017f953501"}, + "membrane_ffmpeg_swscale_plugin": {:hex, :membrane_ffmpeg_swscale_plugin, "0.16.5", "0323608675db448e861b7f9b5d8f1ec3f89ad5683a953eb8b46456f0c2252fe4", [:mix], [{:bundlex, "~> 1.2", [hex: :bundlex, repo: "hexpm", optional: false]}, {:membrane_common_c, "~> 0.16.0", [hex: :membrane_common_c, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.1", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_precompiled_dependency_provider, "~> 0.2.1", [hex: :membrane_precompiled_dependency_provider, repo: "hexpm", optional: false]}, {:membrane_raw_video_format, "~> 0.4.1", [hex: :membrane_raw_video_format, repo: "hexpm", optional: false]}], "hexpm", "c9b2f3328e441eb61127b74230295fee0097b8194c57f4118c09281b2a03cb9d"}, + "membrane_file_plugin": {:hex, :membrane_file_plugin, "0.17.5", "2e65607d68e7c25ce0a1b0dfadbca7b3d5b57859be5c700ed9e865edf7304580", [:mix], [{:logger_backends, "~> 1.0", [hex: :logger_backends, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}], "hexpm", "974c88cb0e7727a8a0a49bb019d7824d4d9092cce2ac666771fe4266d2ea4276"}, + "membrane_h264_ffmpeg_plugin": {:hex, :membrane_h264_ffmpeg_plugin, "0.32.8", "4361ea3852111b874ee37bdc37f6193d73ae3c192b418c7ae1a923b44f122cca", [:mix], [{:bunch, "~> 1.6", [hex: :bunch, repo: "hexpm", optional: false]}, {:bundlex, "~> 1.3", [hex: :bundlex, repo: "hexpm", optional: false]}, {:membrane_common_c, "~> 0.16.0", [hex: :membrane_common_c, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_h264_format, "~> 0.6.1", [hex: :membrane_h264_format, repo: "hexpm", optional: false]}, {:membrane_precompiled_dependency_provider, "~> 0.2.1", [hex: :membrane_precompiled_dependency_provider, repo: "hexpm", optional: false]}, {:membrane_raw_video_format, "~> 0.4.1", [hex: :membrane_raw_video_format, repo: "hexpm", optional: false]}, {:unifex, "~> 1.1", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "ccbc84f610fefceb241eedb3ae5e3e955e9b63d0e6e879d28116de8c6b23fa5b"}, + "membrane_h264_format": {:hex, :membrane_h264_format, "0.6.1", "44836cd9de0abe989b146df1e114507787efc0cf0da2368f17a10c47b4e0738c", [:mix], [], "hexpm", "4b79be56465a876d2eac2c3af99e115374bbdc03eb1dea4f696ee9a8033cd4b0"}, + "membrane_h265_format": {:hex, :membrane_h265_format, "0.2.0", "1903c072cf7b0980c4d0c117ab61a2cd33e88782b696290de29570a7fab34819", [:mix], [], "hexpm", "6df418bdf242c0d9f7dbf2e5aea4c2d182e34ac9ad5a8b8cef2610c290002e83"}, + "membrane_h26x_plugin": {:hex, :membrane_h26x_plugin, "0.11.4", "958aaac3d6908521aac25e483c9caf74ad0448a4ae0d8fb3656733426583e195", [:mix], [{:bunch, "~> 1.4", [hex: :bunch, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_h264_format, "~> 0.6.0", [hex: :membrane_h264_format, repo: "hexpm", optional: false]}, {:membrane_h265_format, "~> 0.2.0", [hex: :membrane_h265_format, repo: "hexpm", optional: false]}], "hexpm", "2284b609fdc6cf9f08d12be8e92cfd9e007c1332b16ec9beb7b4e9219b371f1c"}, + "membrane_mp4_format": {:hex, :membrane_mp4_format, "0.8.1", "ba0032af6527ca9b4bd9b9282436ca43dda206002fc0b27ad3f2cc87f419ee92", [:mix], [], "hexpm", "0e4ec53a50b26a18d6e969f4776606d321ea39bddf5a4571e94f9ccf44e7a53a"}, + "membrane_mp4_plugin": {:hex, :membrane_mp4_plugin, "0.36.11", "49f9bdaddb31a7fb0c7047cb93027058ff0de39c11b9ced28f15b1119983966b", [:mix], [{:bunch, "~> 1.5", [hex: :bunch, repo: "hexpm", optional: false]}, {:membrane_aac_format, "~> 0.8.0", [hex: :membrane_aac_format, repo: "hexpm", optional: false]}, {:membrane_av1_format, "~> 0.3.1", [hex: :membrane_av1_format, repo: "hexpm", optional: false]}, {:membrane_cmaf_format, "~> 0.7.0", [hex: :membrane_cmaf_format, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_file_plugin, "~> 0.17.0", [hex: :membrane_file_plugin, repo: "hexpm", optional: false]}, {:membrane_h264_format, "~> 0.6.1", [hex: :membrane_h264_format, repo: "hexpm", optional: false]}, {:membrane_h265_format, "~> 0.2.0", [hex: :membrane_h265_format, repo: "hexpm", optional: false]}, {:membrane_mp4_format, "~> 0.8.0", [hex: :membrane_mp4_format, repo: "hexpm", optional: false]}, {:membrane_opus_format, "~> 0.3.0", [hex: :membrane_opus_format, repo: "hexpm", optional: false]}, {:membrane_timestamp_queue, "~> 0.2.1", [hex: :membrane_timestamp_queue, repo: "hexpm", optional: false]}], "hexpm", "300d27dbd43632e2e6063ae99bbf42bc9f3495a5761f8bba5274703f3352ed95"}, + "membrane_ogg_plugin": {:hex, :membrane_ogg_plugin, "0.5.2", "32c99c04575b828c4986158a16b91f4d74958cd907e68ea4bdc1e1e1fefcda57", [:mix], [{:crc, "~> 0.10", [hex: :crc, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_opus_format, "~> 0.3.0", [hex: :membrane_opus_format, repo: "hexpm", optional: false]}], "hexpm", "3a80a08c280f9f66ff01dd079a8783200d46aa9713cf4a698a6ef36e374ef187"}, + "membrane_opus_format": {:hex, :membrane_opus_format, "0.3.2", "7751374d26f5d94fe0aaf33cfc121618d1e156eb6c9eaef6c8bd23825179b123", [:mix], [], "hexpm", "5e12deaeca6502b82a6d0b56ae54fa128d27e11b5b573d08d39a55724c62a9bf"}, + "membrane_opus_plugin": {:hex, :membrane_opus_plugin, "0.21.0", "0fcacddfe88ec154f842cc2887e0c993ac99a7fde1b5e8595d22f9266a93a1c8", [:mix], [{:bunch, "~> 1.3", [hex: :bunch, repo: "hexpm", optional: false]}, {:bundlex, "~> 1.2", [hex: :bundlex, repo: "hexpm", optional: false]}, {:membrane_common_c, "~> 0.16.0", [hex: :membrane_common_c, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_opus_format, "~> 0.3.0", [hex: :membrane_opus_format, repo: "hexpm", optional: false]}, {:membrane_precompiled_dependency_provider, "~> 0.2.0", [hex: :membrane_precompiled_dependency_provider, repo: "hexpm", optional: false]}, {:membrane_raw_audio_format, "~> 0.12.0", [hex: :membrane_raw_audio_format, repo: "hexpm", optional: false]}, {:unifex, "~> 1.0", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "663111f56f1feb3e6fc7d3605a653c43b050936f724e37fe27631cdbd52300a3"}, + "membrane_portaudio_plugin": {:hex, :membrane_portaudio_plugin, "0.19.6", "9ceec1405a2ef8b578a5443f7eb7708e864e167810e008e1c9ee8da25150360e", [:mix], [{:bunch, "~> 1.5", [hex: :bunch, repo: "hexpm", optional: false]}, {:membrane_common_c, "~> 0.16.0", [hex: :membrane_common_c, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}, {:membrane_precompiled_dependency_provider, "~> 0.2.1", [hex: :membrane_precompiled_dependency_provider, repo: "hexpm", optional: false]}, {:membrane_raw_audio_format, "~> 0.12.0", [hex: :membrane_raw_audio_format, repo: "hexpm", optional: false]}, {:mockery, "~> 2.1", [hex: :mockery, repo: "hexpm", optional: false]}, {:unifex, "~> 1.2", [hex: :unifex, repo: "hexpm", optional: false]}], "hexpm", "48ba05a9a445305972a6aa778caf15547cef0b2bf0ae89d74d9e6fa669c2240f"}, + "membrane_precompiled_dependency_provider": {:hex, :membrane_precompiled_dependency_provider, "0.2.4", "4aa7d91255d0f325d2350a8c655667d38a3995ba073eef4907d467c399f001e3", [:mix], [{:bundlex, "~> 1.4", [hex: :bundlex, repo: "hexpm", optional: false]}, {:req, "~> 0.5", [hex: :req, repo: "hexpm", optional: false]}], "hexpm", "81c12cbe2c8bc5f547c6a8a11a71e2f55995a312c202bbc9b3ddc60c39818b91"}, + "membrane_raw_audio_format": {:hex, :membrane_raw_audio_format, "0.12.3", "fbbc35e78a39eafdd59d04d931f3490f3104019dc3f3ea20baebbb758b858b44", [:mix], [{:bimap, "~> 1.1", [hex: :bimap, repo: "hexpm", optional: false]}, {:bunch, "~> 1.0", [hex: :bunch, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}], "hexpm", "8e50520ce2ab0405a3a0b2d78a001223bb2d76014aaa4c59398cc21d4187fe26"}, + "membrane_raw_video_format": {:hex, :membrane_raw_video_format, "0.4.5", "b06f509e9f40e05c81e4246461f704e169a592f2379f52fbd7f953e13e139d24", [:mix], [{:image, ">= 0.54.0", [hex: :image, repo: "hexpm", optional: true]}, {:plug, "~> 1.15", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "c4f62b148ecc1643ac2e77e1fda8ee5bd9b595b4047941b02c514a5f310971f2"}, + "membrane_timestamp_queue": {:hex, :membrane_timestamp_queue, "0.2.3", "aa0fd07550bed4d4dc0d0a70ee5525532a9e5f55d2532cfe4be972c605eec203", [:mix], [{:heap, "~> 2.0", [hex: :heap, repo: "hexpm", optional: false]}, {:membrane_core, "~> 1.0", [hex: :membrane_core, repo: "hexpm", optional: false]}], "hexpm", "0600814cbad3b4df80633418abc9b79f171ec7c152282d9735e27772caf54f11"}, "mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"}, "mint": {:hex, :mint, "1.11.0", "a713551624815c0435237b93d90ea8b9b14254690c66f732d0ef8930f76ff1d9", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 1.1", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "c6279ba2d6aa3a383a1d4cfbe7b59f42e6efd400f58d8e2acfeac48a438693ab"}, "mint_web_socket": {:hex, :mint_web_socket, "1.0.6", "5ffcf350df5b90f2d7a04adf877165228804993714592512374218d4679e325a", [:mix], [{:mint, ">= 1.4.1 and < 2.0.0-0", [hex: :mint, repo: "hexpm", optional: false]}], "hexpm", "0c360e9012413f1c115a63532601eb5d63731aab7010949178769760686c1698"}, + "mockery": {:hex, :mockery, "2.5.0", "a87acd74fd733aa3b9cb5663d6f690178b056608f2652f18e4ec423ddd5496ed", [:mix], [], "hexpm", "52492b2eba61055df1c626e894663b624b5e6fdfaaaba1d9a8596236fbf4da69"}, "multigraph": {:hex, :multigraph, "0.16.1-mg.5", "5118665ea3e2eede7244104ccc716b7c517bba44e33c26fb84d7297d77872646", [:mix], [], "hexpm", "d7e3511f1d29e96ed7e7cd01b92bb52eea487b6c61da838f1e61a2ec6838799d"}, "nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"}, "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, "nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"}, + "numbers": {:hex, :numbers, "5.2.5", "47189ba1c0e634f851a76281a2bb7be1914c48498eb1289d16cd50b6c713b436", [:mix], [{:coerce, "~> 1.0.2", [hex: :coerce, repo: "hexpm", optional: false]}, {:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "724563c5b9ed1adccea08b2938215a026aa4344d7506e6b9c75f60d8e2fc9463"}, "nx": {:hex, :nx, "1.0.0", "83d586079cb37d11a4cf8c0edaf2eccafe88aa2369e35ebdb1c3d78c43c8eb33", [:mix], [{:complex, "~> 1.0", [hex: :complex, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "e06c7587efff7a3dfc1e2c92705943e319db20070359e9850c3921aaf26d6998"}, "nx_image": {:hex, :nx_image, "0.2.0", "795780095fd77c4712a2af74b18b7dec9677e474af5c22ffc1d5818099e106be", [:mix], [{:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}], "hexpm", "37276f456e82fb21b8f8b25d64b1889ffac56a9a46171e359ed2d696c712b597"}, "nx_signal": {:hex, :nx_signal, "0.4.0", "a65b9e2f3ab37135fe0d38e0b05bf87820ade9e4b7dc582786256d9f14c9f733", [:mix], [{:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}], "hexpm", "123e90414c212e01dae462576fd44e58254754c01a76f51d0fd84893c51a4a2c"}, @@ -54,11 +87,14 @@ "poolboy": {:hex, :poolboy, "1.5.2", "392b007a1693a64540cead79830443abf5762f5d30cf50bc95cb2c1aaafa006b", [:rebar3], [], "hexpm", "dad79704ce5440f3d5a3681c8590b9dc25d1a561e8f5a9c995281012860901e3"}, "postgrex": {:hex, :postgrex, "0.22.4", "d271f595dfd25230b6398354e19d17bb5e2d20130fd2d9bdca7e15f125d43552", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "4aae45a2d60e35b04eea2602440be152fae332901f1fc7a60fc7cb7f0f9a9c5a"}, "protox": {:hex, :protox, "2.1.0", "af130f17349a34acb3c79a48f05cc2b07fddf7d9951944b92c217c5b439bfa6e", [:mix], [], "hexpm", "89efe4c45eacaa8e8e6347d4be0813b6d5c58d004920a5150d81ea655cbd8cb2"}, + "qex": {:hex, :qex, "0.5.2", "a0c861a2de2380314c23ef592349824ca9016c5845380667ff1d9a22a8796f9b", [:mix], [], "hexpm", "6fb81bf3ae354a9abb471b9561538ea3e8540125d803b00f45cbccff52f00496"}, + "ratio": {:hex, :ratio, "4.0.1", "3044166f2fc6890aa53d3aef0c336f84b2bebb889dc57d5f95cc540daa1912f8", [:mix], [{:decimal, "~> 1.6 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}, {:numbers, "~> 5.2.0", [hex: :numbers, repo: "hexpm", optional: false]}], "hexpm", "c60cbb3ccdff9ffa56e7d6d1654b5c70d9f90f4d753ab3a43a6bf40855b881ce"}, "req": {:hex, :req, "0.7.5", "0c3293cbf7717aba20b1b1b3ea13fe8d3fdf6f1557490f390c3f1ef6dd9db955", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "576853c4bf403faa3c1fa5d093e0759227083b78f8a6864c67d62c0a9c45514d"}, "req_llm": {:hex, :req_llm, "1.29.0", "4f0b2c4da1261fb83f4fe678c741ab45ae9baaa0ffe2779b48b771e58d54e4a2", [:mix], [{:dotenvy, "~> 1.1", [hex: :dotenvy, repo: "hexpm", optional: false]}, {:ex_aws_auth, "~> 1.5", [hex: :ex_aws_auth, repo: "hexpm", optional: true]}, {:finch, "~> 0.22", [hex: :finch, repo: "hexpm", optional: false]}, {:goth, "~> 1.4", [hex: :goth, repo: "hexpm", optional: true]}, {:igniter, "~> 0.7", [hex: :igniter, repo: "hexpm", optional: true]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:jsv, "~> 0.11", [hex: :jsv, repo: "hexpm", optional: false]}, {:llm_db, "~> 2026.10.4", [hex: :llm_db, repo: "hexpm", optional: false]}, {:nimble_options, "~> 1.1", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:req, "~> 0.6", [hex: :req, repo: "hexpm", optional: false]}, {:server_sent_events, "~> 1.1.0", [hex: :server_sent_events, repo: "hexpm", optional: false]}, {:splode, "~> 0.3.0", [hex: :splode, repo: "hexpm", optional: false]}, {:websockex, "~> 0.5.1", [hex: :websockex, repo: "hexpm", optional: false]}, {:zoi, "~> 0.18.11", [hex: :zoi, repo: "hexpm", optional: false]}], "hexpm", "0d632304e9acc6099fc743b18036559e08bcbd5335cab8347f2fa858c691a081"}, "rustler_precompiled": {:hex, :rustler_precompiled, "0.10.1", "2895d3a3239d612c13c18945c0a693e07de4e8f9bc2b6b2297cba3d6576f9eea", [:mix], [{:rustler, "~> 0.28", [hex: :rustler, repo: "hexpm", optional: true]}], "hexpm", "0efa66bc2a4206aec64a2c422ca0b1d69bdc411c7b359ec928feb889357b4abb"}, "safetensors": {:hex, :safetensors, "0.2.0", "d7d37cb91723c09a1bede338bbdd8f7e19f82b8cb41874a0fb7fb02f5f396783", [:mix], [{:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:nx, "~> 1.0", [hex: :nx, repo: "hexpm", optional: false]}], "hexpm", "cc1c095a64256821240208f429acc8b3a8faf47ab08414afcbf13d81d7830ffe"}, "server_sent_events": {:hex, :server_sent_events, "1.1.0", "54606238b9182ba673a10ce90bd95f81a0939c1baa91cdf86b66acc04edd1832", [:mix], [], "hexpm", "8e164db8e295a2d869a8faafbf4a1eeaa749b62fe93f66271adff6394d93ce15"}, + "shmex": {:hex, :shmex, "0.5.2", "5e807c4ec0320fdd3b224d3f8052d501908217a066b67c0433f4cfa369a2b07c", [:mix], [{:bunch_native, "~> 0.5.0", [hex: :bunch_native, repo: "hexpm", optional: false]}, {:bundlex, "~> 1.0", [hex: :bundlex, repo: "hexpm", optional: false]}], "hexpm", "7325f40a7308fecaaab1b19790903034926e5fb202a48fcf51dfd2c4ba97f861"}, "splode": {:hex, :splode, "0.3.3", "420917ee2373c5db8462417ea6faa8cbeb8deec7b18ae5dd2fa07c67f883f25a", [:mix], [], "hexpm", "3f98c7799ec8960f816b4ccc5cc6a5d2b72a20ad3f8fff9199fb530194ad9f50"}, "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"}, "telemetry_metrics": {:hex, :telemetry_metrics, "1.2.0", "7632c19c01d88d8aaca5da1a0e8912f5af39b79e7c08a2c253aeb3c14c2c957e", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "71dde12fc29b58b9c77ec17ec319109e5ca848d010fc1965ed4463bba1837c07"}, @@ -68,6 +104,7 @@ "tokenizers": {:hex, :tokenizers, "0.5.2", "cd9d3a32c86889c0d16320e09ebf329b68c30ea40a4e4bba322eeb82a64323f1", [:mix], [{:castore, "~> 0.1 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: false]}, {:rustler, ">= 0.0.0", [hex: :rustler, repo: "hexpm", optional: true]}, {:rustler_precompiled, "~> 0.6", [hex: :rustler_precompiled, repo: "hexpm", optional: false]}], "hexpm", "0503f9c94ddc0853254125254f84a0e9df8df9700aaf53ddc5a9b0fe78449477"}, "toml": {:hex, :toml, "0.7.0", "fbcd773caa937d0c7a02c301a1feea25612720ac3fa1ccb8bfd9d30d822911de", [:mix], [], "hexpm", "0690246a2478c1defd100b0c9b89b4ea280a22be9a7b313a8a058a2408a2fa70"}, "transmuter": {:git, "https://github.com/georgeguimaraes/transmuter.git", "231028d9ff6f53bd58fa15d9f24d632258369805", [ref: "231028d9ff6f53bd58fa15d9f24d632258369805"]}, + "unifex": {:hex, :unifex, "1.2.5", "b557f7f6c2bfd0c451369a9a29323854674bfca9c60c44d4bccc669c4a28477c", [:mix], [{:bunch, "~> 1.0", [hex: :bunch, repo: "hexpm", optional: false]}, {:bundlex, "~> 1.4", [hex: :bundlex, repo: "hexpm", optional: false]}, {:shmex, "~> 0.5.0", [hex: :shmex, repo: "hexpm", optional: false]}], "hexpm", "7c8d473f8e2b43556d792179d9f6d56ff047c252288dc29a554b5a1e1404e528"}, "unpickler": {:hex, :unpickler, "0.1.0", "c2262c0819e6985b761e7107546cef96a485f401816be5304a65fdd200d5bd6a", [:mix], [], "hexpm", "e2b3f61e62406187ac52afead8a63bfb4e49394028993f3c4c42712743cab79e"}, "unzip": {:hex, :unzip, "0.13.0", "bf5ec6ac6063c69e6ec54c8b4a3b8dcd7a2719d28d10d7025776ab107957cde9", [:mix], [], "hexpm", "4bcb9892ecbf2042606b43ab685a1bffe03c14003e6246f5453db2c829237fd9"}, "websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"}, @@ -76,5 +113,6 @@ "xla": {:hex, :xla, "0.10.0", "41121e9f011456242d3a79b9289910ce43419be0b0e7ebe67cc1292c6b3f232f", [:make, :mix], [{:elixir_make, "~> 0.4", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "f57d91aea6e661b52bf12239316c598679e9170628122bbd941235f040122bc6"}, "yamerl": {:hex, :yamerl, "0.10.0", "4ff81fee2f1f6a46f1700c0d880b24d193ddb74bd14ef42cb0bcf46e81ef2f8e", [:rebar3], [], "hexpm", "346adb2963f1051dc837a2364e4acf6eb7d80097c0f53cbdc3046ec8ec4b4e6e"}, "yaml_elixir": {:hex, :yaml_elixir, "2.12.2", "9dd1330fb4cd9a36a7b0f502e5b12486eff632792ee4a5f0eba52a4d4ec32c9c", [:mix], [{:yamerl, "~> 0.10", [hex: :yamerl, repo: "hexpm", optional: false]}], "hexpm", "e7c1b10122f973e6558462d51c39026ba0e14afbc6745318e990ea82cfe9e159"}, + "zarex": {:hex, :zarex, "1.0.6", "f657ed1187e6e90472e24c92b1fd5bf3f846e74bd240bd77276c13f336a8d168", [:mix], [], "hexpm", "b628a9b0bc312f278af2c288078c31fd4757224b82d768e91bcf3bedbe3a50e7"}, "zoi": {:hex, :zoi, "0.18.11", "d278490068df1b453b1d23cfda3bd66dfe609013fb38ed624387c8bae13b485e", [:mix], [{:decimal, "~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}, {:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.1", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "02786ed534335541b0f21aa3787875019dc91bb5f01e32aba72ce2b987c40640"}, } From e4d2b65f07a61e8b81489f8de131be0b9b65aa1f Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 22:34:24 +0200 Subject: [PATCH 02/12] refactor(providers): share WebSocket open with continuous clients Socket.open/4 connects and completes the upgrade before a deadline and returns the connection to the caller, so a long-lived client can reuse the handshake. Socket.endpoint!/1 validates ws/wss endpoints. --- lib/audio_flow/adapters/providers/socket.ex | 69 ++++++++++++++------- 1 file changed, 48 insertions(+), 21 deletions(-) diff --git a/lib/audio_flow/adapters/providers/socket.ex b/lib/audio_flow/adapters/providers/socket.ex index c12ae68..0ab23f1 100644 --- a/lib/audio_flow/adapters/providers/socket.ex +++ b/lib/audio_flow/adapters/providers/socket.ex @@ -7,36 +7,56 @@ defmodule AudioFlow.Adapters.Providers.Socket do # `decode` maps each `{:text | :binary, data}` frame to a handler event; the # default accepts JSON objects only. def run(url, headers, frames, state, handler, options, decode \\ &json_event/1) do - uri = URI.parse(url) - - unless (uri.scheme in ["ws", "wss"] and uri.host) && is_nil(uri.userinfo), - do: raise(ArgumentError, "expected ws/wss endpoint without user information") - + endpoint!(url) timeout = positive!(options, :timeout_ms, 30_000) limit = positive!(options, :max_response_bytes, 16_777_216) deadline = System.monotonic_time(:millisecond) + timeout - {scheme, port, path} = target(uri) - case Mint.HTTP.connect(scheme, uri.host, port, - mode: :passive, - protocols: [:http1], - transport_opts: [timeout: timeout] - ) do - {:ok, conn} -> + case open(url, headers, deadline, mode: :passive) do + {:ok, conn, ws, ref, pending} -> socket = %{ conn: conn, - ws: nil, - ref: nil, + ws: ws, + ref: ref, deadline: deadline, bytes: 0, limit: limit, decode: decode } - upgrade(socket, scheme, path, headers, {frames, state, handler}) + stream(socket, frames, pending, state, handler) - {:error, _} -> - {:error, :connect_failed} + {:error, _} = error -> + error + end + end + + def endpoint!(url) do + uri = URI.parse(url) + + unless (uri.scheme in ["ws", "wss"] and uri.host) && is_nil(uri.userinfo), + do: raise(ArgumentError, "expected ws/wss endpoint without user information") + + url + end + + # Connects and completes the WebSocket upgrade before `deadline` (monotonic + # milliseconds). The caller owns the connection. `pending` holds responses + # that arrived with the upgrade. Options: `:mode` for `Mint.WebSocket.new/5` + # and extra `:transport_opts`. + def open(url, headers, deadline, options) do + uri = URI.parse(url) + {scheme, port, path} = target(uri) + timeout = max(deadline - System.monotonic_time(:millisecond), 1) + transport = [timeout: timeout] ++ Keyword.get(options, :transport_opts, []) + + case Mint.HTTP.connect(scheme, uri.host, port, + mode: :passive, + protocols: [:http1], + transport_opts: transport + ) do + {:ok, conn} -> upgrade(conn, scheme, path, headers, deadline, options[:mode]) + {:error, _} -> {:error, :connect_failed} end end @@ -47,14 +67,21 @@ defmodule AudioFlow.Adapters.Providers.Socket do {scheme, port, path} end - defp upgrade(%{conn: conn} = socket, scheme, path, headers, {frames, state, handler}) do + defp upgrade(conn, scheme, path, headers, deadline, mode) do {:ok, conn, ref} = check(WS.upgrade(if(scheme == :https, do: :wss, else: :ws), conn, path, headers)) - {conn, status, headers, pending} = handshake(conn, ref, socket.deadline, nil, []) - {:ok, conn, ws} = check(WS.new(conn, ref, status, headers, mode: :passive)) + {conn, status, headers, pending} = handshake(conn, ref, deadline, nil, []) + {:ok, conn, ws} = check(WS.new(conn, ref, status, headers, mode: mode)) + {:ok, conn, ws, ref, pending} + catch + {:provider_socket, reason} -> + Mint.HTTP.close(conn) + {:error, reason} + end - socket = send_frames(%{socket | conn: conn, ws: ws, ref: ref}, frames) + defp stream(socket, frames, pending, state, handler) do + socket = send_frames(socket, frames) loop(socket, pending, state, handler) catch {:provider_socket, reason} -> {:error, reason} From 9156183aebd4983ff0c71a8be2d797c25ac9c9a5 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 22:34:27 +0200 Subject: [PATCH 03/12] feat(chat): add full duplex Moshi conversation mode The Local Moshi full duplex pipeline uses AudioFlow.Duplex. The browser captures the microphone continuously, resamples it to 24 kHz and sends 80 ms chunks with acknowledgement-based flow control, while model audio plays at the same time. CHAT_MODE selects the startup mode; AUDIOFLOW_MOSHI_ENDPOINT is the only endpoint source. --- examples/chat/assets/js/app.js | 3 +- examples/chat/assets/js/audio.js | 6 +- examples/chat/assets/js/duplex.js | 283 +++++++++++++++++ examples/chat/assets/test/duplex.test.js | 263 +++++++++++++++ examples/chat/lib/chat/setup.ex | 57 +++- examples/chat/lib/chat_web/live/chat_live.ex | 309 ++++++++++++++++-- examples/chat/test/duplex_test.exs | 316 +++++++++++++++++++ 7 files changed, 1202 insertions(+), 35 deletions(-) create mode 100644 examples/chat/assets/js/duplex.js create mode 100644 examples/chat/assets/test/duplex.test.js create mode 100644 examples/chat/test/duplex_test.exs diff --git a/examples/chat/assets/js/app.js b/examples/chat/assets/js/app.js index d875912..d3395b4 100644 --- a/examples/chat/assets/js/app.js +++ b/examples/chat/assets/js/app.js @@ -8,12 +8,13 @@ import "live_ai_elements"; import { hooks as liveBase } from "phoenix-colocated/live_base"; import { hooks as liveAiElements } from "phoenix-colocated/live_ai_elements"; import { Player, Recorder } from "./audio"; +import { Duplex } from "./duplex"; const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content"); const liveSocket = new LiveSocket("/live", Socket, { params: { _csrf_token: csrfToken }, - hooks: { ...liveBase, ...liveAiElements, Player, Recorder }, + hooks: { ...liveBase, ...liveAiElements, Duplex, Player, Recorder }, }); liveSocket.connect(); diff --git a/examples/chat/assets/js/audio.js b/examples/chat/assets/js/audio.js index 0b0b79d..5c45b07 100644 --- a/examples/chat/assets/js/audio.js +++ b/examples/chat/assets/js/audio.js @@ -7,7 +7,7 @@ const INPUT_RATE = 16_000; const MAX_SECONDS = 30; -const CAPTURE_WORKLET = ` +export const CAPTURE_WORKLET = ` registerProcessor("capture", class extends AudioWorkletProcessor { process(inputs) { const channel = inputs[0]?.[0]; @@ -30,7 +30,7 @@ for (const type of ["pointerdown", "keydown"]) { document.addEventListener(type, () => playbackContext(), { capture: true }); } -const toBase64 = (bytes) => { +export const toBase64 = (bytes) => { let binary = ""; for (let i = 0; i < bytes.length; i += 0x8000) { binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); @@ -38,7 +38,7 @@ const toBase64 = (bytes) => { return btoa(binary); }; -const fromBase64 = (text) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0)); +export const fromBase64 = (text) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0)); // Box-filter downsampling is enough for speech recognition input. const toPcm16 = (chunks, rate, targetRate = INPUT_RATE) => { diff --git a/examples/chat/assets/js/duplex.js b/examples/chat/assets/js/duplex.js new file mode 100644 index 0000000..9491ed5 --- /dev/null +++ b/examples/chat/assets/js/duplex.js @@ -0,0 +1,283 @@ +// Full duplex conversation with a local Moshi model through AudioFlow.Duplex. +// +// The microphone stays open for the whole conversation. Its samples are +// resampled continuously to 24 kHz and sent as 80 ms s16le chunks. Model audio +// plays at the same time; microphone input never stops or flushes playback. +// +// Flow limits: +// - Before the server reports the model handshake, microphone input is dropped. +// - At most MAX_IN_FLIGHT chunks wait for a server acknowledgement. +// - At most MAX_PENDING chunks wait to be sent; the oldest is dropped first. +// - Model audio more than MAX_PLAYBACK_AHEAD seconds ahead of the clock is dropped. +// - Each conversation has a server generation. Events of another generation +// are ignored. + +import { CAPTURE_WORKLET, fromBase64, toBase64 } from "./audio.js"; + +export const CALL_RATE = 24_000; +export const CHUNK_SAMPLES = 1_920; +export const MAX_IN_FLIGHT = 4; +export const MAX_PENDING = 12; +export const MAX_PLAYBACK_AHEAD = 1; +const PLAYBACK_LEAD = 0.04; + +// Box-filter (area) resampler that keeps its phase between blocks, so the +// result does not depend on how the browser splits the input. +export class StreamResampler { + constructor(inputRate, outputRate) { + if (inputRate < outputRate) throw new Error(`Capture sample rate is below ${outputRate} Hz`); + this.ratio = inputRate / outputRate; + this.sum = 0; + this.filled = 0; + } + + push(samples) { + const out = new Float32Array(Math.ceil((samples.length + this.filled) / this.ratio) + 1); + let count = 0; + for (const sample of samples) { + let left = 1; + while (left > 0) { + const take = Math.min(left, this.ratio - this.filled); + this.sum += sample * take; + this.filled += take; + left -= take; + if (this.filled >= this.ratio - 1e-9) { + out[count++] = this.sum / this.ratio; + this.sum = 0; + this.filled = 0; + } + } + } + return out.subarray(0, count); + } +} + +// Collects float samples into fixed s16le chunks. +export class Chunker { + constructor(size) { + this.buffer = new Int16Array(size); + this.length = 0; + } + + push(samples) { + const chunks = []; + for (const sample of samples) { + const value = Math.max(-1, Math.min(1, sample)); + this.buffer[this.length++] = value < 0 ? value * 0x8000 : value * 0x7fff; + if (this.length === this.buffer.length) { + chunks.push(new Uint8Array(this.buffer.slice().buffer)); + this.length = 0; + } + } + return chunks; + } +} + +export const Duplex = { + mounted() { + this.call = null; + this.onClick = (event) => { + const button = event.target.closest("[data-call]"); + if (!button || button.disabled) return; + if (button.dataset.call === "start") this.start(); + else this.stop(); + }; + this.el.addEventListener("click", this.onClick); + + this.handleEvent("call_ready", ({ generation }) => { + const call = this.current(generation); + if (call) call.ready = true; + }); + this.handleEvent("call_play", ({ generation, pcm, rate }) => { + const call = this.current(generation); + if (call) this.play(call, pcm, rate); + }); + this.handleEvent("call_stopped", ({ generation }) => { + const call = this.current(generation); + if (call) this.release(call); + }); + }, + + destroyed() { + this.el.removeEventListener("click", this.onClick); + this.release(this.call); + }, + + // The server stops the conversation when the LiveView process ends. + disconnected() { + this.release(this.call); + }, + + current(generation) { + return this.call && this.call.generation === generation ? this.call : null; + }, + + async start() { + if (this.call) return; + const call = { + generation: null, + ready: false, + context: null, + stream: null, + node: null, + pending: [], + inFlight: 0, + sent: 0, + dropped: 0, + sources: new Set(), + next: 0, + late: 0, + released: false, + }; + this.call = call; + this.draw("Requesting microphone…"); + + try { + // Created during the click, so the browser allows playback. + call.context = new AudioContext(); + const resampler = new StreamResampler(call.context.sampleRate, CALL_RATE); + const url = URL.createObjectURL(new Blob([CAPTURE_WORKLET], { type: "text/javascript" })); + // A stream that arrives after a stop or a failure is stopped at once. + const media = navigator.mediaDevices + .getUserMedia({ + audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true }, + }) + .then((stream) => { + call.stream = stream; + if (call.released) this.release(call); + return stream; + }); + const [stream] = await Promise.all([ + media, + call.context.audioWorklet.addModule(url).finally(() => URL.revokeObjectURL(url)), + ]); + if (this.call !== call) return; + + const chunker = new Chunker(CHUNK_SAMPLES); + call.node = new AudioWorkletNode(call.context, "capture"); + call.node.port.onmessage = ({ data }) => { + if (this.call !== call || !call.ready) return; + for (const chunk of chunker.push(resampler.push(data))) this.enqueue(call, chunk); + }; + call.context.createMediaStreamSource(stream).connect(call.node); + for (const track of stream.getTracks()) { + track.onended = () => this.fail(call, new Error("Microphone disconnected")); + } + + this.pushEvent("call_start", {}, (reply) => { + if (this.call !== call) { + // Stopped while the server started it. + if (reply?.ok) this.pushEvent("call_stop", { generation: reply.generation }); + return; + } + if (!reply?.ok) return this.release(call); + call.generation = reply.generation; + this.ticker = setInterval(() => this.draw(), 500); + this.draw(); + }); + } catch (error) { + this.fail(call, error); + } + }, + + stop() { + const call = this.call; + if (!call) return; + if (call.generation !== null) this.pushEvent("call_stop", { generation: call.generation }); + this.release(call); + }, + + fail(call, error) { + if (this.call !== call) return this.release(call); + this.release(call); + this.pushEvent("call_failed", { message: error.message }); + }, + + enqueue(call, chunk) { + call.pending.push(chunk); + while (call.pending.length > MAX_PENDING) { + call.pending.shift(); + call.dropped++; + } + this.pump(call); + }, + + pump(call) { + while (call.inFlight < MAX_IN_FLIGHT && call.pending.length > 0) { + const pcm = toBase64(call.pending.shift()); + call.inFlight++; + this.pushEvent("call_audio", { generation: call.generation, pcm }, (reply) => { + if (this.call !== call) return; + call.inFlight--; + if (reply?.ok) call.sent++; + else call.dropped++; + this.pump(call); + }); + } + }, + + play(call, pcm, rate) { + const bytes = fromBase64(pcm); + const samples = new Int16Array(bytes.buffer, 0, bytes.length >> 1); + if (samples.length === 0) return; + + const context = call.context; + const now = context.currentTime; + const start = Math.max(call.next, now + PLAYBACK_LEAD); + if (start - now > MAX_PLAYBACK_AHEAD) { + call.late++; + return; + } + + const buffer = context.createBuffer(1, samples.length, rate); + const channel = buffer.getChannelData(0); + for (let i = 0; i < samples.length; i++) channel[i] = samples[i] / 0x8000; + + const source = context.createBufferSource(); + source.buffer = buffer; + source.connect(context.destination); + source.onended = () => call.sources.delete(source); + source.start(start); + call.sources.add(source); + call.next = start + buffer.duration; + }, + + release(call) { + if (!call) return; + call.released = true; + if (this.call === call) { + this.call = null; + clearInterval(this.ticker); + this.draw(""); + } + if (call.node) { + call.node.port.onmessage = null; + call.node.disconnect(); + } + for (const track of call.stream?.getTracks() ?? []) { + track.onended = null; + track.stop(); + } + for (const source of call.sources) { + source.onended = null; + source.stop(); + } + call.sources.clear(); + call.pending.length = 0; + if (call.context?.state !== "closed") call.context?.close(); + }, + + draw(text) { + const stats = this.el.querySelector("#duplex-stats"); + if (!stats) return; + const call = this.call; + if (text !== undefined || !call) { + stats.textContent = text ?? ""; + return; + } + const queued = Math.max(0, call.next - call.context.currentTime); + stats.textContent = + `Sent ${call.sent} · dropped ${call.dropped} input chunks · ` + + `${Math.round(queued * 1000)} ms queued playback · ${call.late} late output chunks`; + }, +}; diff --git a/examples/chat/assets/test/duplex.test.js b/examples/chat/assets/test/duplex.test.js new file mode 100644 index 0000000..b0d983b --- /dev/null +++ b/examples/chat/assets/test/duplex.test.js @@ -0,0 +1,263 @@ +import { afterEach, test } from "node:test"; +import assert from "node:assert/strict"; + +// Browser fakes: a 48 kHz AudioContext with a settable clock, a microphone +// stream whose tracks record stop(), and a worklet port the test drives. +let contexts = []; +let microphone; +globalThis.document = { addEventListener() {} }; +globalThis.window = { addEventListener() {}, removeEventListener() {} }; +globalThis.AudioContext = class { + constructor() { + this.sampleRate = 48_000; + this.currentTime = 0; + this.state = "running"; + this.sources = []; + this.audioWorklet = { addModule: async () => {} }; + contexts.push(this); + } + close() { + this.state = "closed"; + } + createMediaStreamSource() { + return { connect() {} }; + } + createBuffer(_, samples, rate) { + return { duration: samples / rate, getChannelData: () => new Float32Array(samples) }; + } + createBufferSource() { + const source = { + connect() {}, + start(at) { + source.at = at; + }, + stop() { + source.stopped = true; + }, + }; + this.sources.push(source); + return source; + } +}; +globalThis.AudioWorkletNode = class { + constructor() { + this.port = {}; + microphone.node = this; + } + disconnect() { + this.disconnected = true; + } +}; +Object.defineProperty(globalThis, "navigator", { + configurable: true, + value: { mediaDevices: { getUserMedia: () => microphone.grant() } }, +}); + +const { + Duplex, + StreamResampler, + CHUNK_SAMPLES, + MAX_IN_FLIGHT, + MAX_PENDING, + MAX_PLAYBACK_AHEAD, +} = await import("../js/duplex.js"); + +// A failed assertion must not leave a call (and its status timer) running. +const mounted = []; +afterEach(() => mounted.splice(0).forEach((hook) => hook.destroyed())); + +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +function grantMicrophone() { + const track = { + stop() { + track.stopped = true; + }, + }; + microphone = { track, grant: async () => ({ getTracks: () => [track] }) }; + return microphone; +} + +function mount() { + const handlers = {}; + const pushes = []; + const listeners = {}; + const stats = { textContent: "" }; + const el = { + addEventListener(type, fn) { + listeners[type] = fn; + }, + removeEventListener() {}, + querySelector: () => stats, + }; + const hook = { + ...Duplex, + el, + handleEvent(name, fn) { + handlers[name] = fn; + }, + pushEvent(name, payload, reply) { + pushes.push({ name, payload, reply }); + }, + }; + hook.mounted(); + mounted.push(hook); + const click = (action) => + listeners.click({ target: { closest: () => ({ dataset: { call: action }, disabled: false }) } }); + const sent = (name) => pushes.filter((push) => push.name === name); + return { hook, handlers, pushes, click, sent, stats }; +} + +// Starts a conversation: click, microphone grant, server reply, model handshake. +async function connect(generation = 1) { + const view = mount(); + grantMicrophone(); + view.click("start"); + await tick(); + view.sent("call_start")[0].reply({ ok: true, generation }); + view.handlers.call_ready({ generation }); + return view; +} + +// 80 ms of capture at 48 kHz, in 128-sample worklet blocks. +function speak(blocks = 30, value = 0.5) { + for (let i = 0; i < blocks; i++) { + microphone.node.port.onmessage({ data: new Float32Array(128).fill(value) }); + } +} + +const pcm = (samples) => Buffer.alloc(samples * 2).toString("base64"); + +test("resampler output does not depend on block boundaries", () => { + const input = Float32Array.from({ length: 4_410 }, (_, i) => Math.sin(i / 7)); + const whole = new StreamResampler(44_100, 24_000).push(input); + const split = new StreamResampler(44_100, 24_000); + const parts = []; + for (let i = 0; i < input.length; i += 128) parts.push(...split.push(input.subarray(i, i + 128))); + assert.equal(whole.length, 2_400); + assert.equal(parts.length, whole.length); + parts.forEach((value, i) => assert.ok(Math.abs(value - whole[i]) < 1e-5)); + assert.throws(() => new StreamResampler(16_000, 24_000), /below 24000 Hz/); +}); + +test("capture sends 80 ms 24 kHz chunks only after the model handshake", async () => { + const view = mount(); + grantMicrophone(); + view.click("start"); + await tick(); + speak(60); + assert.equal(view.sent("call_audio").length, 0); + view.sent("call_start")[0].reply({ ok: true, generation: 7 }); + speak(60); + assert.equal(view.sent("call_audio").length, 0); + view.handlers.call_ready({ generation: 7 }); + speak(30); + const [chunk] = view.sent("call_audio"); + assert.equal(chunk.payload.generation, 7); + const bytes = Buffer.from(chunk.payload.pcm, "base64"); + assert.equal(bytes.length, CHUNK_SAMPLES * 2); + assert.equal(bytes.readInt16LE(0), Math.round(0.5 * 0x7fff - 0.5)); +}); + +test("input waits for acknowledgements and drops the oldest chunks past the queue limit", async () => { + const view = await connect(); + speak(30 * (MAX_IN_FLIGHT + MAX_PENDING + 3)); + const audio = () => view.sent("call_audio"); + assert.equal(audio().length, MAX_IN_FLIGHT); + audio()[0].reply({ ok: true }); + assert.equal(audio().length, MAX_IN_FLIGHT + 1); + audio()[1].reply({ ok: false, error: "overloaded" }); + assert.equal(audio().length, MAX_IN_FLIGHT + 2); + view.hook.draw(); + assert.match(view.stats.textContent, /Sent 1 · dropped 4 input chunks/); +}); + +test("model audio plays while the microphone keeps sending", async () => { + const view = await connect(); + const [context] = contexts.slice(-1); + view.handlers.call_play({ generation: 1, pcm: pcm(1_920), rate: 24_000 }); + view.handlers.call_play({ generation: 1, pcm: pcm(1_920), rate: 24_000 }); + speak(30); + view.sent("call_audio")[0].reply({ ok: true }); + speak(30); + view.handlers.call_play({ generation: 1, pcm: pcm(1_920), rate: 24_000 }); + assert.equal(view.sent("call_audio").length, 2); + assert.deepEqual( + context.sources.map((source) => [Number(source.at.toFixed(2)), Boolean(source.stopped)]), + [ + [0.04, false], + [0.12, false], + [0.2, false], + ], + ); +}); + +test("playback drops audio beyond the queue limit and audio of another generation", async () => { + const view = await connect(2); + const [context] = contexts.slice(-1); + for (let i = 0; i < 20; i++) { + view.handlers.call_play({ generation: 2, pcm: pcm(1_920), rate: 24_000 }); + } + const accepted = context.sources.length; + assert.ok(accepted > 1 && accepted < 20); + assert.ok(context.sources.every((source) => source.at <= MAX_PLAYBACK_AHEAD)); + view.handlers.call_play({ generation: 1, pcm: pcm(1_920), rate: 24_000 }); + assert.equal(context.sources.length, accepted); + context.currentTime = 0.5; + view.handlers.call_play({ generation: 2, pcm: pcm(1_920), rate: 24_000 }); + assert.equal(context.sources.length, accepted + 1); +}); + +test("stop releases the microphone, playback and context and ignores later events", async () => { + const view = await connect(3); + const [context] = contexts.slice(-1); + view.handlers.call_play({ generation: 3, pcm: pcm(1_920), rate: 24_000 }); + view.click("stop"); + assert.deepEqual(view.sent("call_stop").at(-1).payload, { generation: 3 }); + assert.ok(microphone.track.stopped); + assert.ok(microphone.node.disconnected); + assert.ok(context.sources.every((source) => source.stopped)); + assert.equal(context.state, "closed"); + view.handlers.call_play({ generation: 3, pcm: pcm(1_920), rate: 24_000 }); + assert.equal(context.sources.length, 1); +}); + +test("server stop, disconnect and a stop during startup all release the call", async () => { + const stopped = await connect(4); + stopped.handlers.call_stopped({ generation: 3 }); + assert.ok(!microphone.track.stopped); + stopped.handlers.call_stopped({ generation: 4 }); + assert.ok(microphone.track.stopped); + + const view = await connect(6); + view.hook.disconnected(); + assert.ok(microphone.track.stopped); + + const early = mount(); + grantMicrophone(); + early.click("start"); + await tick(); + early.click("stop"); + assert.ok(microphone.track.stopped); + early.sent("call_start")[0].reply({ ok: true, generation: 8 }); + assert.deepEqual(early.sent("call_stop").at(-1).payload, { generation: 8 }); +}); + +test("microphone denial and device loss report a failure and release capture", async () => { + const denied = mount(); + microphone = { + grant: async () => { + throw new Error("Permission denied"); + }, + }; + denied.click("start"); + await tick(); + assert.deepEqual(denied.sent("call_failed").at(-1).payload, { message: "Permission denied" }); + assert.equal(contexts.at(-1).state, "closed"); + assert.equal(denied.sent("call_start").length, 0); + + const lost = await connect(9); + microphone.track.onended(); + assert.deepEqual(lost.sent("call_failed").at(-1).payload, { message: "Microphone disconnected" }); + assert.ok(microphone.track.stopped); +}); diff --git a/examples/chat/lib/chat/setup.ex b/examples/chat/lib/chat/setup.ex index d740a7e..5e6fd3b 100644 --- a/examples/chat/lib/chat/setup.ex +++ b/examples/chat/lib/chat/setup.ex @@ -7,7 +7,8 @@ defmodule Chat.Setup do {"local", "Local Apple MLX"}, {"remote", "Deepgram → Chat HTTP → TTS"}, {"openai", "OpenAI speech-to-speech"}, - {"gemini", "Gemini speech-to-speech"} + {"gemini", "Gemini speech-to-speech"}, + {"moshi", "Local Moshi full duplex"} ] @languages ~w(en es fr de ro) @voices ~w(marin cedar) @@ -18,22 +19,35 @@ defmodule Chat.Setup do def voices, do: @voices def tts_providers, do: @tts_providers - def defaults, - do: %{ - "mode" => if(Chat.Engine.native?(), do: "local", else: "demo"), + @moshi_endpoint "ws://127.0.0.1:8998/api/chat" + + @doc "Startup settings. `CHAT_MODE` selects the startup mode." + def defaults(env \\ &System.get_env/1) do + mode = env.("CHAT_MODE") + + %{ + "mode" => + if(Enum.any?(@modes, &(elem(&1, 0) == mode)), + do: mode, + else: if(Chat.Engine.native?(), do: "local", else: "demo") + ), "language" => "en", "voice" => "marin", "tts" => "elevenlabs" } + end def requirements("remote"), do: ["DEEPGRAM_API_KEY", "CHAT_HTTP_ENDPOINT", "CHAT_HTTP_MODEL"] def requirements("openai"), do: ["OPENAI_API_KEY", "OPENAI_REALTIME_MODEL"] def requirements("gemini"), do: ["GEMINI_API_KEY", "GEMINI_LIVE_MODEL"] def requirements(_), do: [] - def rate(%{"mode" => "openai"}), do: 24_000 + def rate(%{"mode" => mode}) when mode in ["openai", "moshi"], do: 24_000 def rate(_), do: 16_000 def speech?(settings), do: settings["mode"] in ["openai", "gemini"] + @doc "Full duplex modes use `AudioFlow.Duplex` instead of a turn-based session." + def duplex?(settings), do: settings["mode"] == "moshi" + def options(s, env \\ &System.get_env/1) do mode = s["mode"] missing = Enum.filter(required(s), &(env.(&1) in [nil, ""])) @@ -45,12 +59,15 @@ defmodule Chat.Setup do not supported?(s) -> {:error, "Unsupported language, voice or TTS"} - mode == "local" and not Chat.Engine.native?() -> - {:error, "Restart with CHAT_PROFILE=native on Apple Silicon"} + unavailable = unavailable(mode) -> + {:error, unavailable} missing != [] -> {:error, "Missing server environment: " <> Enum.join(missing, ", ")} + mode == "moshi" -> + moshi(env.("AUDIOFLOW_MOSHI_ENDPOINT")) + true -> {:ok, build(s, env) ++ [timeout_ms: 120_000, max_events: 4096, max_input_bytes: 1_440_000]} @@ -70,6 +87,32 @@ defmodule Chat.Setup do s["tts"] in @tts_providers end + defp unavailable("local"), + do: unless(Chat.Engine.native?(), do: "Restart with CHAT_PROFILE=native on Apple Silicon") + + defp unavailable("moshi"), + do: + unless(Code.ensure_loaded?(AudioFlow.Duplex.Moshi), + do: "Restart with AUDIOFLOW_MEDIA=1 for full duplex Moshi" + ) + + defp unavailable(_mode), do: nil + + # The endpoint comes only from the server environment, never from the browser. + defp moshi(endpoint) when endpoint in [nil, ""], do: moshi(@moshi_endpoint) + + defp moshi(endpoint) do + case URI.parse(endpoint) do + %URI{scheme: scheme, host: host, userinfo: nil} + when scheme in ["ws", "wss"] and host not in [nil, ""] -> + {:ok, [duplex: {AudioFlow.Duplex.Moshi, [endpoint: endpoint]}]} + + _ -> + {:error, + "AUDIOFLOW_MOSHI_ENDPOINT must be a ws:// or wss:// URL without user information"} + end + end + defp key(env, name), do: fn -> env.(name) end defp build(%{"mode" => "demo"}, _), do: Adapters.Demo.options() ++ [history: true] defp build(%{"mode" => "local"}, _), do: Chat.Stage.session_options() diff --git a/examples/chat/lib/chat_web/live/chat_live.ex b/examples/chat/lib/chat_web/live/chat_live.ex index f6dcdf3..adf8c95 100644 --- a/examples/chat/lib/chat_web/live/chat_live.ex +++ b/examples/chat/lib/chat_web/live/chat_live.ex @@ -8,10 +8,16 @@ defmodule ChatWeb.ChatLive do message shows that partial text. When recording stops, the complete audio is one session turn. Reply audio is pushed to the browser as it arrives, and the complete reply is kept as a WAV file for replay. + + The full duplex mode (local Moshi) has no turns. It uses `AudioFlow.Duplex`: + the browser sends 80 ms chunks of 24 kHz PCM continuously, and the model + audio and text come back at the same time. Each conversation has a + generation number; events from an earlier generation are ignored. """ use Phoenix.LiveView alias AudioFlow.Audio + alias AudioFlow.Duplex alias AudioFlow.Recording.Store alias AudioFlow.Text alias Chat.Catalog @@ -28,27 +34,35 @@ defmodule ChatWeb.ChatLive do # Start a partial transcription after this much new audio (0.5 s). @partial_bytes 16_000 + # One duplex input chunk: 80 ms of 24 kHz mono s16le PCM. + @call_chunk_bytes 3_840 + # Model text after this much silence starts a new message. + @call_segment_ms 1_500 + @call_max_messages 200 + @call_max_message_bytes 4_000 @impl true def mount(_params, _session, socket) do - session = + settings = Setup.defaults() + + {session, setup_error} = if connected?(socket) do Phoenix.PubSub.subscribe(Chat.PubSub, Chat.Engine.topic()) Process.send_after(self(), :retention, 60_000) - - {:ok, session} = - AudioFlow.start_session( - elem(Setup.options(Setup.defaults()), 1) ++ [output: {Chat.Output, self()}] - ) - - session + open_session(settings) + else + {nil, nil} end {:ok, assign(socket, session: session, - settings: Setup.defaults(), - setup_error: nil, + settings: settings, + setup_error: setup_error, + call: nil, + call_status: "idle", + call_error: nil, + generation: 0, capture: nil, artifacts: [], playback_turn: nil, @@ -71,7 +85,9 @@ defmodule ChatWeb.ChatLive do @impl true def handle_event("send", %{"text" => text}, socket) do - case if(Setup.speech?(socket.assigns.settings), do: "", else: String.trim(text)) do + settings = socket.assigns.settings + + case if(Setup.speech?(settings) or Setup.duplex?(settings), do: "", else: String.trim(text)) do "" -> {:reply, %{ok: false}, socket} @@ -81,6 +97,10 @@ defmodule ChatWeb.ChatLive do end end + def handle_event(event, _params, %{assigns: %{session: nil}} = socket) + when event in ["recording", "pause", "resume", "capture"], + do: {:noreply, assign(socket, setup_error: "Not available without a turn-based session.")} + def handle_event("recording", _params, socket) do socket = cancel(socket) |> add_message("user", "", pending: true, live: true) id = List.last(socket.assigns.messages).id @@ -157,9 +177,56 @@ defmodule ChatWeb.ChatLive do def handle_event("new_chat", _params, socket) do socket = cancel(socket) if socket.assigns.session, do: AudioFlow.clear_history(socket.assigns.session) - {:noreply, assign(socket, messages: [])} + call = socket.assigns.call && %{socket.assigns.call | reply_id: nil} + {:noreply, assign(socket, messages: [], call: call)} + end + + def handle_event("call_start", _params, socket) do + cond do + not Setup.duplex?(socket.assigns.settings) -> + {:reply, %{ok: false, error: "Select the full duplex pipeline first."}, socket} + + socket.assigns.call -> + {:reply, %{ok: false, error: "A conversation is already active."}, socket} + + true -> + # The adapter and endpoint come from the server settings, not from params. + case Setup.options(socket.assigns.settings) do + {:ok, [duplex: adapter]} -> start_call(socket, adapter) + {:error, message} -> {:reply, %{ok: false, error: message}, call_error(socket, message)} + end + end + end + + def handle_event( + "call_audio", + %{"generation" => generation, "pcm" => pcm}, + %{assigns: %{call: %{generation: generation, ready: true} = call}} = socket + ) + when is_binary(pcm) do + with true <- byte_size(pcm) <= div(@call_chunk_bytes * 4, 3) + 4, + {:ok, <<_::binary-size(@call_chunk_bytes)>> = data} <- Base.decode64(pcm), + :ok <- Duplex.push(call.pid, %Audio{data: data, sample_rate: 24_000}) do + {:reply, %{ok: true}, socket} + else + {:error, reason} -> {:reply, %{ok: false, error: describe(reason)}, socket} + _ -> {:reply, %{ok: false, error: "invalid_chunk"}, socket} + end + end + + def handle_event("call_audio", _params, socket), + do: {:reply, %{ok: false, error: "stale"}, socket} + + def handle_event("call_stop", %{"generation" => generation}, socket) do + case socket.assigns.call do + %{generation: ^generation} -> {:noreply, stop_call(socket, "idle")} + _ -> {:noreply, socket} + end end + def handle_event("call_failed", %{"message" => message}, socket) when is_binary(message), + do: {:noreply, call_error(socket, "Microphone error: " <> String.slice(message, 0, 200))} + def handle_event("select_model", %{"_target" => [field]} = params, socket) when field in ["stt", "llm", "voice"] do result = Chat.Engine.select(String.to_existing_atom(field), params[field]) @@ -176,17 +243,18 @@ defmodule ChatWeb.ChatLive do {:error, message} -> {:noreply, assign(socket, setup_error: message)} - {:ok, options} -> - if socket.assigns.recording || socket.assigns.turn do + {:ok, _options} -> + if socket.assigns.recording || socket.assigns.turn || socket.assigns.call do {:noreply, assign(socket, - setup_error: "Stop the current turn/recording before changing settings." + setup_error: + "Stop the current turn, recording or conversation before changing settings." )} else socket = cancel(socket) - AudioFlow.stop_session(socket.assigns.session) + if socket.assigns.session, do: AudioFlow.stop_session(socket.assigns.session) Chat.Capture.close(socket.assigns.capture) - {:ok, session} = AudioFlow.start_session(options ++ [output: {Chat.Output, self()}]) + {session, setup_error} = open_session(settings) {:noreply, assign(socket, @@ -195,7 +263,9 @@ defmodule ChatWeb.ChatLive do messages: [], capture: nil, artifacts: [], - setup_error: nil + setup_error: setup_error, + call_status: "idle", + call_error: nil )} end end @@ -270,8 +340,150 @@ defmodule ChatWeb.ChatLive do end end + defp open_session(settings) do + case Setup.options(settings) do + {:ok, [duplex: _]} -> + {nil, nil} + + {:ok, options} -> + {:ok, session} = AudioFlow.start_session(options ++ [output: {Chat.Output, self()}]) + {session, nil} + + {:error, message} -> + {nil, message} + end + end + + defp start_call(socket, adapter) do + generation = socket.assigns.generation + 1 + socket = assign(socket, generation: generation) + + case start_duplex(adapter) do + {:ok, pid} -> + call = %{ + pid: pid, + monitor: Process.monitor(pid), + generation: generation, + ready: false, + reply_id: nil, + text_at: nil + } + + {:reply, %{ok: true, generation: generation}, + assign(socket, call: call, call_status: "connecting", call_error: nil)} + + {:error, reason} -> + message = "Cannot start the conversation: " <> describe(reason) + {:reply, %{ok: false, error: message}, call_error(socket, message)} + end + end + + # Duplex.start_link/1 raises for options that it cannot use. + defp start_duplex(adapter) do + Duplex.start_link(owner: self(), adapter: adapter) + rescue + error in ArgumentError -> {:error, Exception.message(error)} + end + + defp call_event(socket, :ready) do + %{call: call} = socket.assigns + socket = add_message(socket, "assistant", "", pending: true, live: true) + + socket + |> assign( + call: %{call | ready: true, reply_id: List.last(socket.assigns.messages).id}, + call_status: "live" + ) + |> push_event("call_ready", %{generation: call.generation}) + end + + defp call_event(socket, {:audio, %Audio{data: data, sample_rate: rate}}) do + push_event(socket, "call_play", %{ + generation: socket.assigns.call.generation, + pcm: Base.encode64(data), + rate: rate + }) + end + + defp call_event(socket, {:text, text}), do: call_text(socket, text) + + defp call_event(socket, {:error, reason}), + do: call_error(socket, "Conversation error: " <> describe(reason)) + + defp call_event(socket, :closed), do: stop_call(socket, "closed") + defp call_event(socket, _event), do: socket + + # Moshi does not mark turns. A pause in the model text starts a new message, + # and the conversation keeps only the latest messages. + defp call_text(socket, text) do + %{call: call, messages: messages} = socket.assigns + now = System.monotonic_time(:millisecond) + current = call.reply_id && Enum.find(messages, &(&1.id == call.reply_id)) + + socket = + if current == nil or (call.text_at != nil and now - call.text_at >= @call_segment_ms) or + byte_size(current.text) >= @call_max_message_bytes do + socket = if current, do: settle(socket, current.id), else: socket + socket = add_message(socket, "assistant", "") + assign(socket, call: %{call | reply_id: List.last(socket.assigns.messages).id}) + else + socket + end + + %{call: call} = socket.assigns + + socket + |> update_message(call.reply_id, fn message -> + text = if message.text == "", do: String.trim_leading(text), else: text + %{message | text: message.text <> text, pending: false, live: false} + end) + |> then(&assign(&1, messages: Enum.take(&1.assigns.messages, -@call_max_messages))) + |> assign(call: %{call | text_at: now}) + end + + # A message without model text is removed; otherwise it stops waiting. + defp settle(socket, id) do + case Enum.find(socket.assigns.messages, &(&1.id == id)) do + %{text: ""} -> remove_message(socket, id) + %{} -> update_message(socket, id, &%{&1 | pending: false, live: false}) + nil -> socket + end + end + + defp call_error(socket, message), do: stop_call(socket, "error", message) + + # Stops the conversation process and tells the browser to release the + # microphone and the queued playback of this generation. + defp stop_call(socket, status, error \\ nil) do + socket = + case socket.assigns.call do + nil -> + socket + + call -> + Process.demonitor(call.monitor, [:flush]) + + try do + Duplex.stop(call.pid) + catch + :exit, _ -> :ok + end + + socket + |> settle(call.reply_id) + |> push_event("call_stopped", %{generation: call.generation}) + end + + assign(socket, call: nil, call_status: status, call_error: error) + end + + defp describe(reason) when is_binary(reason), do: reason + defp describe(reason) when is_atom(reason), do: Atom.to_string(reason) + defp describe(reason), do: inspect(reason) + @impl true def terminate(_, socket) do + stop_call(socket, "closed") Chat.Capture.close(socket.assigns.capture) if socket.assigns.session, do: AudioFlow.stop_session(socket.assigns.session) :ok @@ -332,6 +544,18 @@ defmodule ChatWeb.ChatLive do do: {:noreply, capture_event(socket, event)} def handle_info({AudioFlow, _, _, _}, socket), do: {:noreply, socket} + + def handle_info({Duplex, pid, event}, %{assigns: %{call: %{pid: pid}}} = socket), + do: {:noreply, call_event(socket, event)} + + def handle_info({Duplex, _, _}, socket), do: {:noreply, socket} + + def handle_info( + {:DOWN, ref, :process, _, reason}, + %{assigns: %{call: %{monitor: ref}}} = socket + ), + do: {:noreply, call_error(socket, "Conversation stopped: " <> describe(reason))} + def handle_info({:models, models}, socket), do: {:noreply, assign(socket, models: models)} def handle_info({ref, result}, %{assigns: %{recording: %{task: ref} = recording}} = socket) do @@ -579,6 +803,16 @@ defmodule ChatWeb.ChatLive do else: "The largest combinations may not fit in memory." end + defp call_label("connecting"), do: "Connecting to Moshi…" + defp call_label("live"), do: "Live: microphone and playback on" + defp call_label("closed"), do: "Conversation ended" + defp call_label("error"), do: "Stopped by an error" + defp call_label(_), do: "Not connected" + + defp call_variant("live"), do: "default" + defp call_variant("error"), do: "destructive" + defp call_variant(_), do: "secondary" + defp gb(value), do: :erlang.float_to_binary(value * 1.0, decimals: 1) @impl true @@ -587,7 +821,8 @@ defmodule ChatWeb.ChatLive do assign(assigns, stt_models: Catalog.stt(), llm_models: Catalog.llm(), - voices: Catalog.voices() + voices: Catalog.voices(), + duplex: Setup.duplex?(assigns.settings) ) ~H""" @@ -596,7 +831,9 @@ defmodule ChatWeb.ChatLive do

AudioFlow chat

- Type a message, or record one with the microphone. + {if @duplex, + do: "Start a conversation and talk. You and Moshi can speak at the same time.", + else: "Type a message, or record one with the microphone."}

New chat @@ -636,7 +873,7 @@ defmodule ChatWeb.ChatLive do > {voice} - +

{@setup_error}

@@ -645,13 +882,16 @@ defmodule ChatWeb.ChatLive do

Synthetic demo: fixed transcript, echoed text, silent PCM. No inference.

+

+ Full duplex: the microphone stays open and Moshi audio plays at the same time. Input is sent in 80 ms chunks. Moshi speaks English only and does not transcribe you. Use headphones to prevent echo. The server connects to AUDIOFLOW_MOSHI_ENDPOINT. +

Microphone only; fresh provider connection each turn, no history replay. No text/audio alignment or native history truncation is claimed. Language and Gemini voice use provider defaults.

Remote chain requires DEEPGRAM_API_KEY, CHAT_HTTP_ENDPOINT, CHAT_HTTP_MODEL and ELEVENLABS_API_KEY / ELEVENLABS_VOICE_ID or CARTESIA_API_KEY / CARTESIA_VOICE_ID. Optional CHAT_HTTP_API_KEY. Speech-to-speech requires OPENAI_API_KEY / OPENAI_REALTIME_MODEL or GEMINI_API_KEY / GEMINI_LIVE_MODEL. Configure these on the server.

-

@@ -752,13 +992,34 @@ defmodule ChatWeb.ChatLive do -

+
{if @paused, do: "Web Audio suspended", else: "Playback running or awaiting endpoint"}
- +
+ + Start conversation + + + Stop + +
+ + {call_label(@call_status)} + +
+ +
+ "moshi"}[&1])["mode"] == "moshi" + assert Chat.Setup.defaults(&%{"CHAT_MODE" => "nope"}[&1])["mode"] == "demo" + assert Chat.Setup.rate(%{"mode" => "moshi"}) == 24_000 + end + + test "the Moshi endpoint comes only from AUDIOFLOW_MOSHI_ENDPOINT" do + settings = %{Chat.Setup.defaults(fn _ -> nil end) | "mode" => "moshi"} + + if Code.ensure_loaded?(AudioFlow.Duplex.Moshi) do + assert {:ok, [duplex: {AudioFlow.Duplex.Moshi, [endpoint: "ws://127.0.0.1:8998/api/chat"]}]} = + Chat.Setup.options(settings, fn _ -> nil end) + + env = &%{"AUDIOFLOW_MOSHI_ENDPOINT" => "ws://10.0.0.2:9000/api/chat"}[&1] + + assert {:ok, [duplex: {_, [endpoint: "ws://10.0.0.2:9000/api/chat"]}]} = + Chat.Setup.options(settings, env) + + for endpoint <- ["http://127.0.0.1:8998/api/chat", "ws://user:secret@127.0.0.1/api/chat"] do + assert {:error, message} = + Chat.Setup.options(settings, &%{"AUDIOFLOW_MOSHI_ENDPOINT" => endpoint}[&1]) + + assert message =~ "AUDIOFLOW_MOSHI_ENDPOINT" + end + else + assert {:error, "Restart with AUDIOFLOW_MEDIA=1" <> _} = + Chat.Setup.options(settings, fn _ -> nil end) + end + end +end + +if Code.ensure_loaded?(AudioFlow.Duplex.Moshi) do + defmodule Chat.DuplexTest do + use ExUnit.Case, async: false + import Phoenix.ConnTest + import Phoenix.LiveViewTest + + alias Membrane.Ogg.Opus, as: OggOpus + alias Membrane.Ogg.Page + alias Membrane.Ogg.Parser + alias Membrane.Opus.Decoder.Native, as: Decoder + alias Membrane.Opus.Encoder.Native, as: Encoder + + @endpoint ChatWeb.Endpoint + @chunk 3_840 + + # A local Moshi wire peer: handshake byte, then one 80 ms Ogg Opus page and + # the scripted text for each 80 ms frame that the client sends. With + # `answer: false` it reads input and sends no audio. + defmodule Moshi do + @behaviour WebSock + + def init({owner, script, answer}) do + head = + Page.create_first(1) + |> Page.append_packet!(OggOpus.create_id_header(1)) + |> Page.finalize(0) + + state = %{ + owner: owner, + script: script, + answer: answer, + buffer: <<>>, + continued: nil, + decoder: Decoder.create(24_000, 1), + encoder: Encoder.create(24_000, 1, 2049, -1000, 3001), + frames: 0 + } + + send(owner, {:moshi, :connected}) + {:push, [{:binary, <<0>>}, {:binary, <<1>> <> Page.serialize(head)}], state} + end + + def handle_in({<<1, data::binary>>, opcode: :binary}, state) do + {packets, continued, rest} = Parser.parse(state.buffer <> data, state.continued) + + pcm = + for %Parser.Packet{payload: packet} <- packets, + not String.starts_with?(packet, ["OpusHead", "OpusTags"]), + into: <<>>, + do: Decoder.decode_packet(state.decoder, packet) + + frames = div(byte_size(pcm), 3_840) + if frames > 0, do: send(state.owner, {:moshi, :input_frames, frames}) + + replies = + Enum.flat_map(state.frames..(state.frames + frames - 1)//1, fn index -> + [{:binary, <<1>> <> output(state, index)}] ++ + for text <- List.wrap(state.script[index]), do: {:binary, <<2>> <> text} + end) + + {:push, if(state.answer, do: replies, else: []), + %{state | buffer: rest, continued: continued, frames: state.frames + frames}} + end + + def handle_info(_message, state), do: {:ok, state} + + defp output(state, index) do + page = %Page{bos: false, bitstream_serial_number: 1, page_sequence_number: index + 1} + + for _ <- 1..4, reduce: page do + page -> + {:ok, packet} = Encoder.encode_packet(state.encoder, :binary.copy(<<0, 0>>, 480), 480) + Page.append_packet!(page, packet) + end + |> Page.finalize((index + 1) * 3_840) + |> Page.serialize() + end + end + + defmodule Server do + def init(options), do: options + + def call(conn, options), + do: conn |> WebSockAdapter.upgrade(Moshi, options, []) |> Plug.Conn.halt() + end + + setup do + for name <- ["CHAT_MODE", "AUDIOFLOW_MOSHI_ENDPOINT"] do + original = System.get_env(name) + + on_exit(fn -> + if original, do: System.put_env(name, original), else: System.delete_env(name) + end) + end + + System.put_env("CHAT_MODE", "moshi") + :ok + end + + defp moshi(script, answer \\ true) do + server = + start_supervised!( + Supervisor.child_spec( + {Bandit, + plug: {Server, {self(), script, answer}}, + port: 0, + ip: {127, 0, 0, 1}, + startup_log: false}, + id: make_ref() + ) + ) + + {:ok, {_, port}} = ThousandIsland.listener_info(server) + System.put_env("AUDIOFLOW_MOSHI_ENDPOINT", "ws://127.0.0.1:#{port}/api/chat") + end + + defp chunk(byte \\ 1), do: Base.encode64(:binary.copy(<>, div(@chunk, 2))) + defp call(view), do: :sys.get_state(view.pid).socket.assigns.call + + defp connect(view) do + # A browser-supplied endpoint is ignored; the server environment wins. + render_hook(view, "call_start", %{"endpoint" => "ws://127.0.0.1:1/api/chat"}) + assert_reply(view, %{ok: true, generation: generation}) + assert_receive {:moshi, :connected}, 2_000 + assert_push_event(view, "call_ready", %{generation: ^generation}, 2_000) + generation + end + + test "CHAT_MODE=moshi opens the duplex controls instead of turn-based input" do + {:ok, view, _} = live(build_conn(), "/") + html = render(view) + assert html =~ "Start conversation" + assert html =~ "Not connected" + assert html =~ "Active: moshi" + refute has_element?(view, "#prompt") + refute has_element?(view, "#recorder") + assert has_element?(view, "button[phx-click=capture][disabled]") + assert has_element?(view, "button[data-call=stop][disabled]") + assert :sys.get_state(view.pid).socket.assigns.session == nil + end + + test "microphone input and model output flow at the same time until stop" do + moshi(%{0 => " Hi", 1 => " there."}) + {:ok, view, _} = live(build_conn(), "/") + generation = connect(view) + assert render(view) =~ "Live: microphone and playback on" + assert has_element?(view, "button[data-call=start][disabled]") + + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + assert_reply(view, %{ok: true}) + assert_receive {:moshi, :input_frames, 1}, 2_000 + assert_push_event(view, "call_play", %{generation: ^generation, rate: 24_000, pcm: pcm}) + assert byte_size(Base.decode64!(pcm)) == @chunk + + # Model audio arrived; the next input is still accepted and answered. + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + assert_reply(view, %{ok: true}) + assert_receive {:moshi, :input_frames, 1}, 2_000 + assert_push_event(view, "call_play", %{generation: ^generation}) + assert eventually(fn -> render(view) =~ "Hi there." end) + + %{pid: duplex} = call(view) + monitor = Process.monitor(duplex) + render_hook(view, "call_stop", %{"generation" => generation}) + assert_receive {:DOWN, ^monitor, :process, ^duplex, :normal} + assert_push_event(view, "call_stopped", %{generation: ^generation}) + assert render(view) =~ "Not connected" + assert render(view) =~ "Hi there." + + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + assert_reply(view, %{ok: false, error: "stale"}) + end + + test "input chunks are bounded, generation-checked and rejected before the handshake" do + moshi(%{}) + {:ok, view, _} = live(build_conn(), "/") + + render_hook(view, "call_audio", %{"generation" => 1, "pcm" => chunk()}) + assert_reply(view, %{ok: false, error: "stale"}) + + generation = connect(view) + + for pcm <- [Base.encode64(<<0, 0>>), Base.encode64(:binary.copy(<<0>>, 4 * @chunk)), "%%"] do + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => pcm}) + assert_reply(view, %{ok: false, error: "invalid_chunk"}) + end + + render_hook(view, "call_audio", %{"generation" => generation + 1, "pcm" => chunk()}) + assert_reply(view, %{ok: false, error: "stale"}) + assert call(view).generation == generation + end + + test "input that the model has not answered for 2 s is refused, and the call stays open" do + moshi(%{}, false) + {:ok, view, _} = live(build_conn(), "/") + generation = connect(view) + + for _ <- 1..25 do + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + assert_reply(view, %{ok: true}) + end + + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + assert_reply(view, %{ok: false, error: "overloaded"}) + assert render(view) =~ "Live: microphone and playback on" + end + + test "settings and a second conversation are refused while one is active" do + moshi(%{}) + {:ok, view, _} = live(build_conn(), "/") + connect(view) + + render_hook(view, "call_start", %{}) + assert_reply(view, %{ok: false, error: "A conversation is already active."}) + view |> element("#configuration") |> render_submit(%{"mode" => "demo"}) + assert render(view) =~ "Stop the current turn, recording or conversation" + assert render(view) =~ "Active: moshi" + end + + test "microphone denial and an unreachable model stop the conversation with an error" do + moshi(%{}) + {:ok, view, _} = live(build_conn(), "/") + generation = connect(view) + %{pid: duplex} = call(view) + monitor = Process.monitor(duplex) + render_hook(view, "call_failed", %{"message" => "Permission denied"}) + assert_receive {:DOWN, ^monitor, :process, ^duplex, :normal} + assert_push_event(view, "call_stopped", %{generation: ^generation}) + assert has_element?(view, "[role=alert]", "Microphone error: Permission denied") + + {:ok, closed} = :gen_tcp.listen(0, ip: {127, 0, 0, 1}) + {:ok, port} = :inet.port(closed) + :gen_tcp.close(closed) + System.put_env("AUDIOFLOW_MOSHI_ENDPOINT", "ws://127.0.0.1:#{port}/api/chat") + render_hook(view, "call_start", %{}) + assert_reply(view, %{ok: true, generation: failed}) + assert_push_event(view, "call_stopped", %{generation: ^failed}, 2_000) + assert has_element?(view, "[role=alert]", "Conversation error: connect_failed") + assert render(view) =~ "Stopped by an error" + assert has_element?(view, "button[data-call=start]:not([disabled])") + end + + test "model text after a pause starts a new message" do + moshi(%{0 => " One.", 30 => " Two."}) + {:ok, view, _} = live(build_conn(), "/") + generation = connect(view) + + push = fn -> + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) + end + + push.() + assert eventually(fn -> render(view) =~ "One." end) + Process.sleep(1_600) + + for _ <- 1..30 do + push.() + assert_receive {:moshi, :input_frames, 1}, 2_000 + end + + assert eventually(fn -> render(view) =~ "Two." end) + + texts = + for %{role: "assistant", text: text} <- :sys.get_state(view.pid).socket.assigns.messages, + do: text + + assert texts == ["One.", "Two."] + end + + defp eventually(fun, tries \\ 100) + defp eventually(_, 0), do: false + + defp eventually(fun, tries) do + if fun.() do + true + else + Process.sleep(20) + eventually(fun, tries - 1) + end + end + end +end From 7d3ca3c5746e732e1ec8192841207c823a26adb6 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 22:34:30 +0200 Subject: [PATCH 04/12] docs(chat): document full duplex Moshi setup and limits --- README.md | 4 +- examples/chat/README.md | 84 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e321b81..fd45bae 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,9 @@ mix audio_flow.bench --runs 20 --concurrency 4 For a browser chat with typed and spoken messages, see [examples/chat](examples/chat/README.md). Its Linux demo needs no model download; the app also exposes server-configured speech providers, languages, redacted -recordings, playback progress and provisional pause/resume. +recordings, playback progress and provisional pause/resume. Its full duplex +mode talks to a local Moshi server through `AudioFlow.Duplex`: the microphone +stays open and the model audio plays at the same time. To build agents as node graphs, see [ui](ui/README.md). It is a local dashboard with a canvas editor and an MCP endpoint for coding agents. A session runs an diff --git a/examples/chat/README.md b/examples/chat/README.md index a53da75..6302035 100644 --- a/examples/chat/README.md +++ b/examples/chat/README.md @@ -4,7 +4,7 @@ A local LiveView chat over one AudioFlow session per browser tab. Type a message, or record one with the microphone. While you record, the user message shows a live transcript. The reply text streams into the conversation, the reply audio plays as it arrives, and each reply keeps an audio player for -replay. The UI uses [live_shadcn](https://live-shadcn-storybook.fly.dev/) and +replay. A full duplex mode talks to a local Moshi model without turns. The UI uses [live_shadcn](https://live-shadcn-storybook.fly.dev/) and its AI Elements components. The native profile runs models on Apple Silicon through MLX (macOS 26.2+). @@ -27,6 +27,81 @@ Demo STT returns a fixed “Hello”, replies echo the input and output PCM is s It tests session wiring, not recognition or synthesis. No EMLX, EXLA, Bumblebee or model downloads are needed. Use the same profile for all Mix commands. +## Full duplex conversation with local Moshi + +This mode has no turns. The microphone stays open, and Moshi audio plays at +the same time. You can speak while Moshi speaks; your speech does not stop the +playback. It uses `AudioFlow.Duplex` with `AudioFlow.Duplex.Moshi`. It needs +`AUDIOFLOW_MEDIA=1` (Ogg Opus through Membrane) and no Whisper, Qwen or Kokoro +download. The demo profile starts no native model. + +1. Start the Moshi server in a separate terminal. The model + `kyutai/moshika-mlx-q4` loads from the Hugging Face cache + (`~/.cache/huggingface/hub/models--kyutai--moshika-mlx-q4`). If the cache is + empty, the first start downloads approximately 5 GB. `HF_HUB_OFFLINE=1` + prevents network access when the model is in the cache. + + ```sh + HF_HUB_OFFLINE=1 uvx --python 3.12 --from moshi_mlx python -m moshi_mlx.local_web \ + -q 4 --hf-repo kyutai/moshika-mlx-q4 --no-browser --port 8998 + ``` + +2. Start the chat in full duplex mode: + + ```sh + cd examples/chat + export CHAT_PROFILE=demo AUDIOFLOW_MEDIA=1 CHAT_MODE=moshi + mix setup + mix phx.server + ``` + +3. Open , click **Start conversation** and allow the + microphone. Click **Stop** to end the conversation. + +Use the same three variables for all Mix commands of this profile. The build +goes to `_build/demo_media`, so it does not reuse modules from another profile +(`_build` native, `_build/demo` demo, `_build/native_media` native with media). +Without `CHAT_MODE=moshi`, select **Local Moshi full duplex** in the Pipeline +list and click **Apply**. + +The server reads the model endpoint only from `AUDIOFLOW_MOSHI_ENDPOINT` +(default `ws://127.0.0.1:8998/api/chat`). The value must be a `ws://` or +`wss://` URL without user information. Browser events never select the +endpoint. + +Status and errors show next to the controls: **Connecting to Moshi…**, **Live**, +**Conversation ended** or **Stopped by an error** with the reason (for +example `connect_failed` when the Moshi server does not run, or the microphone +error). The text input, the record button, the pause controls and the +recordings control are not available in this mode. Moshi does not transcribe +you, so only the model text shows. A pause of 1.5 s in the model text starts a +new message. + +Limits: + +| Item | Limit | +| --- | --- | +| Input chunk | exactly 3,840 bytes: 80 ms of 24 kHz mono s16le PCM. Other sizes are refused. | +| Resampling | continuous box filter from the capture rate to 24 kHz. Capture below 24 kHz fails. | +| Input before the model handshake | dropped | +| Input that waits for a server acknowledgement | 4 chunks (320 ms) | +| Input that waits to be sent | 12 chunks (960 ms); the oldest chunk is dropped first | +| Input that the model has not answered | 2 s (`AudioFlow.Duplex` `:max_input_lead_ms`); more is refused with `overloaded` and dropped | +| Queued model audio in the browser | 1 s ahead of the playback clock; later chunks are dropped | +| Time | 15 s to the model handshake; 30 s without accepted input ends the conversation; 30 min in total | +| Conversation messages | the latest 200, 4,000 bytes each | + +The status line shows the sent and dropped input chunks, the queued playback +and the dropped model audio. Each conversation has a generation number; the +browser and the server ignore events of an earlier generation. Stop, an +error, a microphone failure or disconnection, a LiveView disconnect and a +server stop release the microphone, the queued playback and the model +connection. The Moshi server serves one connection at a time. + +Use headphones. The browser requests echo cancellation, but AudioFlow does not +verify it. Without headphones, Moshi can hear its own voice. Microphone access +requires `localhost` or HTTPS. + ## Run native models on Apple Silicon The repository `mise.toml` pins Erlang, Elixir, Node.js, and @@ -226,11 +301,14 @@ Chat validation commands: ```sh cd examples/chat CHAT_PROFILE=demo mix test -node --test assets/test/audio.test.js +CHAT_PROFILE=demo AUDIOFLOW_MEDIA=1 mix test +node --test assets/test/ CHAT_PROFILE=demo mix assets.build ``` -The JS test uses a simulated AudioContext clock, not a browser speaker. +The JS tests use a simulated AudioContext clock and microphone, not a browser +speaker. With `AUDIOFLOW_MEDIA=1`, the duplex LiveView tests use a local +WebSocket peer with the Moshi wire format, not the Moshi model. Implementation validation on Linux (synthetic/local fixtures only): 7 chat ExUnit tests, 1 simulated AudioContext test, and 51 relevant core tests passed; From d5bf6040344c64aa936bcfb060afd4ba99a9a5c4 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 22:34:36 +0200 Subject: [PATCH 05/12] refactor(moshi): share Ogg Opus framing and the WebSocket fixture AudioFlow.Moshi.Codec holds the Moshi wire kinds and the Ogg page and Opus packet coding, so a continuous client can reuse them. The local Moshi fixture moves to test/support with manual handshake and reply controls. --- lib_media/audio_flow/adapters/moshi.ex | 81 +++----------- lib_media/audio_flow/moshi/codec.ex | 86 +++++++++++++++ test/moshi_test.exs | 90 +--------------- test/support/moshi_server.ex | 139 +++++++++++++++++++++++++ 4 files changed, 240 insertions(+), 156 deletions(-) create mode 100644 lib_media/audio_flow/moshi/codec.ex create mode 100644 test/support/moshi_server.ex diff --git a/lib_media/audio_flow/adapters/moshi.ex b/lib_media/audio_flow/adapters/moshi.ex index 811176f..85cffb0 100644 --- a/lib_media/audio_flow/adapters/moshi.ex +++ b/lib_media/audio_flow/adapters/moshi.ex @@ -21,21 +21,12 @@ defmodule AudioFlow.Adapters.Moshi do @behaviour AudioFlow.Adapter alias AudioFlow.Adapters.Providers.Socket alias AudioFlow.Audio - alias Membrane.Ogg.Opus, as: OggOpus - alias Membrane.Ogg.Page - alias Membrane.Ogg.Parser - alias Membrane.Opus.Decoder.Native, as: Decoder - alias Membrane.Opus.Encoder.Native, as: Encoder + alias AudioFlow.Moshi.Codec @rate 24_000 - # Moshi steps every 80 ms; Opus packets are 20 ms. + # Moshi steps every 80 ms. @frame 1_920 - @packet 480 @lead @frame * 6 - # libopus OPUS_APPLICATION_AUDIO, OPUS_AUTO bitrate, OPUS_SIGNAL_VOICE. - @application 2049 - @bitrate -1000 - @signal 3001 def run(audio, options, emit) do Socket.audio!(audio, @rate) @@ -51,11 +42,7 @@ defmodule AudioFlow.Adapters.Moshi do received: 0, last_text: nil, ready: false, - encoder: Encoder.create(@rate, 1, @application, @bitrate, @signal), - decoder: Decoder.create(@rate, 1), - buffer: <<>>, - continued: nil, - page: nil, + codec: Codec.new(), emit: emit } @@ -66,7 +53,7 @@ defmodule AudioFlow.Adapters.Moshi do state, &event/2, Keyword.put_new(options, :timeout_ms, 60_000), - &decode/1 + &Codec.wire/1 ) end @@ -77,19 +64,10 @@ defmodule AudioFlow.Adapters.Moshi do end end - defp decode({:binary, <<0>>}), do: {:ok, :ready} - defp decode({:binary, <<1, data::binary>>}), do: {:ok, {:audio, data}} - - defp decode({:binary, <<2, text::binary>>}), - do: if(String.valid?(text), do: {:ok, {:text, text}}, else: :error) - - defp decode(_frame), do: :error - defp event(:ready, %{ready: false} = state) do - head = header(Page.create_first(:rand.uniform(0xFFFFFFFF) - 1), OggOpus.create_id_header(1)) - tags = header(Page.create_subsequent(head), OggOpus.create_comment_header()) - headers = {:binary, <<1>> <> Page.serialize(head) <> Page.serialize(tags)} - {state, frames} = top_up(%{state | ready: true, page: tags}, state.input_samples + @lead) + {codec, headers} = Codec.headers(state.codec) + state = %{state | ready: true, codec: codec} + {state, frames} = top_up(state, state.input_samples + @lead) {:cont, state, [headers | frames]} end @@ -106,14 +84,9 @@ defmodule AudioFlow.Adapters.Moshi do end defp event({:audio, data}, state) do - case parse(state.buffer <> data, state.continued) do - {:ok, packets, continued, rest} -> - pcm = - for %Parser.Packet{payload: packet} <- packets, not opus_header?(packet), into: <<>> do - Decoder.decode_packet(state.decoder, packet) - end - - state = %{state | buffer: rest, continued: continued} + case Codec.decode(state.codec, data) do + {:ok, codec, pcm} -> + state = %{state | codec: codec} :ok = emit_reply(pcm, state) received(%{state | received: state.received + div(byte_size(pcm), 2)}) @@ -122,20 +95,6 @@ defmodule AudioFlow.Adapters.Moshi do end end - # Parser.parse/2 keeps partial pages in `rest` and raises on a corrupt page. - defp parse(bytes, continued) do - {packets, continued, rest} = Parser.parse(bytes, continued) - {:ok, packets, continued, rest} - rescue - RuntimeError -> :error - end - - defp opus_header?(<<"OpusHead", _::binary>>), do: true - defp opus_header?(<<"OpusTags", _::binary>>), do: true - defp opus_header?(_packet), do: false - - defp header(page, packet), do: page |> Page.append_packet!(packet) |> Page.finalize(0) - defp emit_reply(pcm, state) do skip = max(state.input_samples - state.received, 0) * 2 @@ -181,22 +140,8 @@ defmodule AudioFlow.Adapters.Moshi do do: binary_part(state.input, state.sent * 2, @frame * 2), else: :binary.copy(<<0>>, @frame * 2) - packets = - for <> do - {:ok, packet} = Encoder.encode_packet(state.encoder, chunk, @packet) - packet - end - - sent = state.sent + @frame - - # One page per frame, so the server gets each frame at once. Ogg Opus - # granule positions count 48 kHz samples. - page = - packets - |> Enum.reduce(Page.create_subsequent(state.page), &Page.append_packet!(&2, &1)) - |> Page.finalize(sent * 2) - - state = %{state | sent: sent, page: page} - top_up(state, target, [{:binary, <<1>> <> Page.serialize(page)} | frames]) + {codec, frame} = Codec.encode(state.codec, pcm) + state = %{state | sent: state.sent + @frame, codec: codec} + top_up(state, target, [frame | frames]) end end diff --git a/lib_media/audio_flow/moshi/codec.ex b/lib_media/audio_flow/moshi/codec.ex new file mode 100644 index 0000000..5ef74b8 --- /dev/null +++ b/lib_media/audio_flow/moshi/codec.ex @@ -0,0 +1,86 @@ +defmodule AudioFlow.Moshi.Codec do + @moduledoc false + # Moshi wire framing: binary WebSocket messages with a one-byte kind, `0` + # handshake, `1` Ogg Opus audio (24 kHz mono), `2` UTF-8 text. Client audio + # is one Ogg page per 80 ms frame, four 20 ms Opus packets per page, so the + # server gets each frame at once. + alias Membrane.Ogg.Opus, as: OggOpus + alias Membrane.Ogg.Page + alias Membrane.Ogg.Parser + alias Membrane.Opus.Decoder.Native, as: Decoder + alias Membrane.Opus.Encoder.Native, as: Encoder + + @rate 24_000 + @frame 1_920 + @packet 480 + # libopus OPUS_APPLICATION_AUDIO, OPUS_AUTO bitrate, OPUS_SIGNAL_VOICE. + @application 2049 + @bitrate -1000 + @signal 3001 + + def rate, do: @rate + def frame_samples, do: @frame + + def new do + %{ + encoder: Encoder.create(@rate, 1, @application, @bitrate, @signal), + decoder: Decoder.create(@rate, 1), + buffer: <<>>, + continued: nil, + page: nil, + granule: 0 + } + end + + def wire({:binary, <<0>>}), do: {:ok, :ready} + def wire({:binary, <<1, data::binary>>}), do: {:ok, {:audio, data}} + + def wire({:binary, <<2, text::binary>>}), + do: if(String.valid?(text), do: {:ok, {:text, text}}, else: :error) + + def wire(_frame), do: :error + + def headers(codec) do + head = header(Page.create_first(:rand.uniform(0xFFFFFFFF) - 1), OggOpus.create_id_header(1)) + tags = header(Page.create_subsequent(head), OggOpus.create_comment_header()) + {%{codec | page: tags}, {:binary, <<1>> <> Page.serialize(head) <> Page.serialize(tags)}} + end + + defp header(page, packet), do: page |> Page.append_packet!(packet) |> Page.finalize(0) + + # `pcm` is exactly one 80 ms frame. Ogg Opus granule positions count 48 kHz + # samples. + def encode(codec, <>) do + granule = codec.granule + @frame * 2 + + page = + for <>, + reduce: Page.create_subsequent(codec.page) do + page -> + {:ok, packet} = Encoder.encode_packet(codec.encoder, chunk, @packet) + Page.append_packet!(page, packet) + end + |> Page.finalize(granule) + + {%{codec | page: page, granule: granule}, {:binary, <<1>> <> Page.serialize(page)}} + end + + # Returns the PCM of all complete Opus packets. Partial pages stay buffered. + def decode(codec, data) do + {packets, continued, rest} = Parser.parse(codec.buffer <> data, codec.continued) + + pcm = + for %Parser.Packet{payload: packet} <- packets, not opus_header?(packet), into: <<>> do + Decoder.decode_packet(codec.decoder, packet) + end + + {:ok, %{codec | buffer: rest, continued: continued}, pcm} + rescue + # Parser.parse/2 raises on a corrupt page. + RuntimeError -> :error + end + + defp opus_header?(<<"OpusHead", _::binary>>), do: true + defp opus_header?(<<"OpusTags", _::binary>>), do: true + defp opus_header?(_packet), do: false +end diff --git a/test/moshi_test.exs b/test/moshi_test.exs index db734c2..0097038 100644 --- a/test/moshi_test.exs +++ b/test/moshi_test.exs @@ -3,96 +3,10 @@ if System.get_env("AUDIOFLOW_MEDIA") == "1" do use ExUnit.Case, async: true alias AudioFlow.Adapters.Moshi alias AudioFlow.Audio - alias Membrane.Ogg.Opus, as: OggOpus - alias Membrane.Ogg.Page - alias Membrane.Ogg.Parser - alias Membrane.Opus.Decoder.Native, as: Decoder - alias Membrane.Opus.Encoder.Native, as: Encoder + alias AudioFlow.Test.MoshiServer @frame 1_920 - # Answers each client frame with one 80 ms output page, then the text - # scripted for that frame, like moshi_mlx.local_web. - defmodule Server do - @behaviour WebSock - - def init({owner, script}) do - state = %{ - owner: owner, - script: script, - buffer: <<>>, - continued: nil, - decoder: Decoder.create(24_000, 1), - encoder: Encoder.create(24_000, 1, 2049, -1000, 3001), - frames: 0 - } - - head = - Page.create_first(1) - |> Page.append_packet!(OggOpus.create_id_header(1)) - |> Page.finalize(0) - - {:push, [{:binary, <<0>>}, {:binary, <<1>> <> Page.serialize(head)}], state} - end - - def handle_in({<<1, data::binary>>, opcode: :binary}, state) do - {packets, continued, rest} = Parser.parse(state.buffer <> data, state.continued) - - pcm = - for %Parser.Packet{payload: packet} <- packets, - not String.starts_with?(packet, ["OpusHead", "OpusTags"]), - into: <<>>, - do: Decoder.decode_packet(state.decoder, packet) - - send(state.owner, {:client_pcm, pcm}) - frames = div(byte_size(pcm), 2 * 1_920) - - replies = - Enum.flat_map(state.frames..(state.frames + frames - 1)//1, fn index -> - [{:binary, <<1>> <> output(state, index)}] ++ - for text <- List.wrap(state.script[index]), do: {:binary, <<2>> <> text} - end) - - {:push, replies, - %{state | buffer: rest, continued: continued, frames: state.frames + frames}} - end - - def handle_info(_message, state), do: {:ok, state} - - defp output(state, index) do - packets = - for _ <- 1..4 do - {:ok, packet} = Encoder.encode_packet(state.encoder, :binary.copy(<<0, 0>>, 480), 480) - packet - end - - page = %Page{bos: false, bitstream_serial_number: 1, page_sequence_number: index + 1} - - packets - |> Enum.reduce(page, &Page.append_packet!(&2, &1)) - |> Page.finalize((index + 1) * 3_840) - |> Page.serialize() - end - end - - defmodule Endpoint do - def init(options), do: options - - def call(conn, options), - do: conn |> WebSockAdapter.upgrade(Server, options, []) |> Plug.Conn.halt() - end - - defp endpoint(script) do - server = - start_supervised!( - {Bandit, - plug: {Endpoint, {self(), script}}, port: 0, ip: {127, 0, 0, 1}, startup_log: false} - ) - - {:ok, {_, port}} = ThousandIsland.listener_info(server) - "ws://127.0.0.1:#{port}/api/chat" - end - defp run(script, options) do owner = self() @@ -102,7 +16,7 @@ if System.get_env("AUDIOFLOW_MEDIA") == "1" do do: <> input = %Audio{data: tone, sample_rate: 24_000} - options = [endpoint: endpoint(script)] ++ options + options = [endpoint: MoshiServer.endpoint(owner, script: script)] ++ options Moshi.run(input, options, fn event -> send(owner, {:output, event}) diff --git a/test/support/moshi_server.ex b/test/support/moshi_server.ex new file mode 100644 index 0000000..2fb4f3e --- /dev/null +++ b/test/support/moshi_server.ex @@ -0,0 +1,139 @@ +if Code.ensure_loaded?(Membrane.Ogg.Parser) do + defmodule AudioFlow.Test.MoshiServer do + @moduledoc """ + Local Moshi WebSocket fixture with the `moshi_mlx.local_web` framing. + + It sends `{:moshi_server, pid}` to the owner, then the handshake and the + Ogg Opus head page. For each client message it sends `{:client_pcm, pcm}` + with the decoded PCM, then answers each 80 ms frame with one 80 ms silent + output page and the `:script` text for that frame index. On exit it sends + `:moshi_server_closed`. + + Options: `:script` (map of frame index to text), `handshake: :manual` + (send `:handshake` to the pid), `reply: :manual` (send `:reply` to answer + the frames received so far). Send `:close` to close the connection. + """ + @behaviour WebSock + alias Membrane.Ogg.Opus, as: OggOpus + alias Membrane.Ogg.Page + alias Membrane.Ogg.Parser + alias Membrane.Opus.Decoder.Native, as: Decoder + alias Membrane.Opus.Encoder.Native, as: Encoder + + @frame 1_920 + + def endpoint(owner, options \\ []) do + server = + ExUnit.Callbacks.start_supervised!( + {Bandit, + plug: {__MODULE__.Endpoint, {owner, options}}, + port: 0, + ip: {127, 0, 0, 1}, + startup_log: false} + ) + + {:ok, {_, port}} = ThousandIsland.listener_info(server) + "ws://127.0.0.1:#{port}/api/chat" + end + + defmodule Endpoint do + @moduledoc false + def init(options), do: options + + def call(conn, options) do + conn + |> WebSockAdapter.upgrade(AudioFlow.Test.MoshiServer, options, []) + |> Plug.Conn.halt() + end + end + + @impl true + def init({owner, options}) do + send(owner, {:moshi_server, self()}) + + state = %{ + owner: owner, + script: Keyword.get(options, :script, %{}), + reply: Keyword.get(options, :reply, :auto), + buffer: <<>>, + continued: nil, + decoder: Decoder.create(24_000, 1), + encoder: Encoder.create(24_000, 1, 2049, -1000, 3001), + received: 0, + answered: 0 + } + + case Keyword.get(options, :handshake, :auto) do + :auto -> {:push, handshake(), state} + :manual -> {:ok, state} + end + end + + @impl true + def handle_in({<<1, data::binary>>, opcode: :binary}, state) do + {packets, continued, rest} = Parser.parse(state.buffer <> data, state.continued) + + pcm = + for %Parser.Packet{payload: packet} <- packets, + not String.starts_with?(packet, ["OpusHead", "OpusTags"]), + into: <<>>, + do: Decoder.decode_packet(state.decoder, packet) + + send(state.owner, {:client_pcm, pcm}) + + state = %{ + state + | buffer: rest, + continued: continued, + received: state.received + div(byte_size(pcm), 2 * @frame) + } + + if state.reply == :auto, do: answer(state), else: {:ok, state} + end + + @impl true + def handle_info(:handshake, state), do: {:push, handshake(), state} + def handle_info(:reply, state), do: answer(state) + def handle_info(:close, state), do: {:stop, :normal, state} + + @impl true + def terminate(_reason, state) do + send(state.owner, :moshi_server_closed) + :ok + end + + defp handshake do + head = + Page.create_first(1) + |> Page.append_packet!(OggOpus.create_id_header(1)) + |> Page.finalize(0) + + [{:binary, <<0>>}, {:binary, <<1>> <> Page.serialize(head)}] + end + + defp answer(state) do + replies = + Enum.flat_map(state.answered..(state.received - 1)//1, fn index -> + [{:binary, <<1>> <> output(state, index)}] ++ + for text <- List.wrap(state.script[index]), do: {:binary, <<2>> <> text} + end) + + {:push, replies, %{state | answered: state.received}} + end + + defp output(state, index) do + packets = + for _ <- 1..4 do + {:ok, packet} = Encoder.encode_packet(state.encoder, :binary.copy(<<0, 0>>, 480), 480) + packet + end + + page = %Page{bos: false, bitstream_serial_number: 1, page_sequence_number: index + 1} + + packets + |> Enum.reduce(page, &Page.append_packet!(&2, &1)) + |> Page.finalize((index + 1) * 3_840) + |> Page.serialize() + end + end +end From 8a9d5e628af8a105db60ea51619ede07660dff45 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 22:34:36 +0200 Subject: [PATCH 06/12] feat(duplex): add continuous full-duplex Moshi sessions AudioFlow.Duplex keeps one model connection open. Microphone input and model output flow at the same time, with no committed turn, silence gate or output drop. It starts asynchronously, emits :ready after the Moshi handshake, monitors the owner, and bounds unanswered input, push size, owner mailbox, connect, idle and total time. AudioFlow.Duplex.Moshi sends each 80 ms frame as one Ogg Opus page. --- docs/providers.md | 56 ++++ lib/audio_flow/duplex.ex | 403 +++++++++++++++++++++++++ lib/audio_flow/duplex/adapter.ex | 41 +++ lib_media/audio_flow/adapters/moshi.ex | 6 +- lib_media/audio_flow/duplex/moshi.ex | 80 +++++ test/duplex_test.exs | 256 ++++++++++++++++ 6 files changed, 840 insertions(+), 2 deletions(-) create mode 100644 lib/audio_flow/duplex.ex create mode 100644 lib/audio_flow/duplex/adapter.ex create mode 100644 lib_media/audio_flow/duplex/moshi.ex create mode 100644 test/duplex_test.exs diff --git a/docs/providers.md b/docs/providers.md index 2a6eaff..5bfd123 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -190,6 +190,62 @@ AUDIOFLOW_MOSHI_PCM=question.s16le mix test test/moshi_test.exs `AUDIOFLOW_MOSHI_ENDPOINT` overrides the default endpoint. +### Continuous full-duplex Moshi + +`AudioFlow.Duplex` keeps one Moshi connection open. Microphone input and model +output flow at the same time. There is no committed turn, no end-of-turn +detection, no silence gate, and no output drop while the user speaks. Use it +for a live conversation. Use `AudioFlow.Adapters.Moshi` for one committed turn. + +```elixir +{:ok, duplex} = + AudioFlow.Duplex.start_link( + owner: self(), + adapter: {AudioFlow.Duplex.Moshi, endpoint: "ws://127.0.0.1:8998/api/chat"}) + +# Wait for {AudioFlow.Duplex, ^duplex, :ready}, then push 80 ms chunks: +:ok = AudioFlow.Duplex.push(duplex, %AudioFlow.Audio{data: pcm_3840_bytes, sample_rate: 24_000}) +:ok = AudioFlow.Duplex.stop(duplex) +``` + +`start_link/1` returns before the connection opens. The owner receives +`{AudioFlow.Duplex, pid, event}`, where `event` is `:ready` (after the Moshi +handshake), `{:audio, %AudioFlow.Audio{}}`, `{:text, token}`, +`{:error, reason}` or `:closed`. `:closed` comes last, also after an error. +`push/2` returns `{:error, :not_ready}` before `:ready` and `{:error, :closed}` +after the session stops. Keep the endpoint in server configuration; the browser +does not need it. + +The adapter sends each complete 80 ms frame (3,840 bytes at 24 kHz) as one Ogg +page at once. A shorter remainder waits for the next push. Moshi answers each +input frame with one output frame, so the client must push continuous audio, +silence included, to get continuous output. + +Bounds (defaults): + +- `:connect_timeout_ms` (15,000) from start to the Moshi handshake. +- `:idle_timeout_ms` (30,000) without an accepted push. +- `:max_session_ms` (1,800,000) in total. +- `:max_chunk_bytes` (48,000) for each push, else `{:error, :too_large}`. +- `:max_input_lead_ms` (2,000) of pushed audio that model audio has not + answered. A push past it returns `{:error, :overloaded}` and is not sent, for + example while MLX warms up. +- `:max_owner_queue` (250): when the owner mailbox has this many messages, the + session fails with `:owner_overloaded`. Output is not buffered or dropped. +- `:send_timeout_ms` (5,000) for each TCP write. + +The session monitors the owner and closes the connection when the owner exits. +On failure, timeout and `stop/1` it exits with reason `:normal`, so the link +from `start_link/1` does not stop the owner. The owner must be a local process. +The Moshi server limits above also apply: one connection at a time, and model +state continues across connections. + +`mix test test/duplex_test.exs` (with `AUDIOFLOW_MEDIA=1`) checks simultaneous +input and output, frame sizes, the handshake gate, the input and owner bounds, +timeouts and connection cleanup against a local fixture. With +`AUDIOFLOW_HTTP_MODEL_TESTS=1` and `AUDIOFLOW_MOSHI_PCM`, it also streams the +question and then silence in real time to a running server. + ## Bounds, cancellation and errors All providers accept `:endpoint` overrides for proxies and local tests. Use diff --git a/lib/audio_flow/duplex.ex b/lib/audio_flow/duplex.ex new file mode 100644 index 0000000..106c4d7 --- /dev/null +++ b/lib/audio_flow/duplex.ex @@ -0,0 +1,403 @@ +defmodule AudioFlow.Duplex do + @schema NimbleOptions.new!( + owner: [type: :pid, required: true, doc: "Receives the session messages."], + adapter: [ + type: {:tuple, [:atom, :keyword_list]}, + required: true, + doc: "`{module, options}` that implements `AudioFlow.Duplex.Adapter`." + ], + connect_timeout_ms: [ + type: :pos_integer, + default: 15_000, + doc: "Time from start to the model handshake." + ], + idle_timeout_ms: [ + type: :pos_integer, + default: 30_000, + doc: "Time after `:ready` or the last accepted push." + ], + max_session_ms: [type: :pos_integer, default: 1_800_000, doc: "Total session time."], + max_chunk_bytes: [type: :pos_integer, default: 48_000, doc: "Largest push."], + max_input_lead_ms: [ + type: :pos_integer, + default: 2_000, + doc: "Pushed audio not yet answered by model audio." + ], + max_owner_queue: [ + type: :pos_integer, + default: 250, + doc: "Owner mailbox length that fails the session." + ], + send_timeout_ms: [type: :pos_integer, default: 5_000, doc: "TCP send timeout."] + ) + + @moduledoc """ + One continuous full-duplex model connection. Input and output flow at the + same time. There are no turns: no end-of-turn detection, no silence gate and + no output drop while the user speaks. For committed turns, use + `AudioFlow.Session`. + + {:ok, duplex} = + AudioFlow.Duplex.start_link(owner: self(), adapter: {AudioFlow.Duplex.Moshi, []}) + + receive do + {AudioFlow.Duplex, ^duplex, :ready} -> :ok + end + + :ok = AudioFlow.Duplex.push(duplex, %AudioFlow.Audio{data: pcm, sample_rate: 24_000}) + + `start_link/1` returns before the connection opens. The owner then receives + `{AudioFlow.Duplex, pid, event}` messages: + + * `:ready` after the model handshake. `push/2` returns + `{:error, :not_ready}` before it. + * `{:audio, %AudioFlow.Audio{}}` and `{:text, text}` with model output, in + wire order. + * `{:error, reason}` when the session fails. `:closed` follows. + * `:closed` once, when the session stops for any reason except owner exit. + + Failure reasons: `:connect_failed`, `:connect_timeout`, `{:http_status, status}`, + `:idle_timeout`, `:session_timeout`, `:connection_closed`, `:socket_error`, + `:invalid_frame`, `:invalid_event`, `:owner_overloaded`, `:send_failed` and + adapter reasons. + + The session stops when the owner exits. It stops with reason `:normal` on + failure, timeout and `stop/1`, so a link to it does not stop the owner. + + ## Bounds + + Input that the model has not answered is at most `:max_input_lead_ms`. + A push past that bound returns `{:error, :overloaded}` and the chunk is not + sent. Output is sent to the owner at once and is not buffered. If the owner + mailbox has `:max_owner_queue` messages or more, the session fails with + `:owner_overloaded`. The owner must be a local process. + + """ <> NimbleOptions.docs(@schema) + use GenServer + alias AudioFlow.Adapters.Providers.Socket + alias AudioFlow.Audio + alias Mint.WebSocket, as: WS + + @call_timeout 5_000 + + @doc "Starts a session. Raises `ArgumentError` for invalid options." + def start_link(options) do + options = NimbleOptions.validate!(options, @schema) + owner = options[:owner] + + unless node(owner) == node(), do: raise(ArgumentError, "owner must be a local process") + + {module, adapter_options} = options[:adapter] + Code.ensure_loaded!(module) + config = module.config(adapter_options) + Socket.endpoint!(config.url) + GenServer.start_link(__MODULE__, {options, module, config}) + end + + @doc """ + Sends one mono s16le chunk at the adapter sample rate. Returns `:ok` after + the frames are written to the socket. + + These errors leave the session open: `:not_ready`, `:invalid_audio`, + `:too_large`, `:overloaded` and `:timeout` (no answer in 5 s). `:closed` + means the session stopped. Other reasons fail the session. + """ + def push(pid, audio) when is_pid(pid) do + GenServer.call(pid, {:push, audio}, @call_timeout) + catch + :exit, {:timeout, _} -> {:error, :timeout} + :exit, _ -> {:error, :closed} + end + + @doc "Stops the session and closes the connection. Returns `:ok` if it already stopped." + def stop(pid) when is_pid(pid) do + GenServer.stop(pid, :normal, @call_timeout) + catch + :exit, _ -> :ok + end + + @impl true + def init({options, module, config}) do + Process.flag(:trap_exit, true) + owner = options[:owner] + server = self() + lead = div(options[:max_input_lead_ms] * config.sample_rate, 1000) + + connector = + spawn_link(fn -> + send( + server, + {:connector, self(), + connect(server, config, options[:connect_timeout_ms], options[:send_timeout_ms])} + ) + end) + + {:ok, + %{ + owner: owner, + owner_ref: Process.monitor(owner), + owner_alive: true, + module: module, + adapter: module.init(config.options), + rate: config.sample_rate, + phase: :connecting, + connector: connector, + conn: nil, + ws: nil, + ref: nil, + pushed: 0, + received: 0, + max_lead: lead, + max_chunk: options[:max_chunk_bytes], + max_queue: options[:max_owner_queue], + idle_ms: options[:idle_timeout_ms], + connect_timer: :erlang.start_timer(options[:connect_timeout_ms], self(), :connect), + session_timer: :erlang.start_timer(options[:max_session_ms], self(), :session), + idle_timer: nil + }} + end + + @impl true + def handle_call({:push, _audio}, _from, %{phase: phase} = state) when phase != :ready, + do: {:reply, {:error, :not_ready}, state} + + def handle_call({:push, audio}, _from, state) do + with :ok <- check_audio(audio, state), + {:ok, frames, adapter} <- state.module.handle_audio(audio, state.adapter), + {:ok, state} <- send_frames(%{state | adapter: adapter}, frames) do + state = %{state | pushed: state.pushed + div(byte_size(audio.data), 2)} + {:reply, :ok, restart_idle(state)} + else + {:error, reason} when reason in [:invalid_audio, :too_large, :overloaded] -> + {:reply, {:error, reason}, state} + + {:error, reason, state} -> + fail({:error, reason}, state, reason) + + {:error, reason} -> + fail({:error, reason}, state, reason) + end + end + + defp check_audio(%Audio{} = audio, state) do + samples = div(byte_size(audio.data), 2) + + cond do + not Audio.valid?(audio) or audio.sample_rate != state.rate -> {:error, :invalid_audio} + byte_size(audio.data) > state.max_chunk -> {:error, :too_large} + state.pushed + samples - state.received > state.max_lead -> {:error, :overloaded} + true -> :ok + end + end + + defp check_audio(_audio, _state), do: {:error, :invalid_audio} + + defp fail(reply, state, reason) do + notify!(state, {:error, reason}) + {:stop, :normal, reply, state} + end + + @impl true + def handle_info({:DOWN, ref, :process, _, _}, %{owner_ref: ref} = state), + do: {:stop, :normal, %{state | owner_alive: false}} + + def handle_info({:EXIT, pid, reason}, %{connector: pid} = state) do + state = %{state | connector: nil} + if reason == :normal, do: {:noreply, state}, else: failed(state, :connect_failed) + end + + def handle_info({:EXIT, _pid, _reason}, state), do: {:noreply, state} + + def handle_info({:timeout, timer, kind}, state) do + case {kind, state} do + {:connect, %{connect_timer: ^timer}} -> failed(state, :connect_timeout) + {:session, %{session_timer: ^timer}} -> failed(state, :session_timeout) + {:idle, %{idle_timer: ^timer}} -> failed(state, :idle_timeout) + _stale -> {:noreply, state} + end + end + + def handle_info({:connector, pid, {:ok, conn, ws, ref, pending}}, %{connector: pid} = state) do + case Mint.HTTP.set_mode(conn, :active) do + {:ok, conn} -> + responses(%{state | conn: conn, ws: ws, ref: ref, phase: :open}, pending) + + {:error, _} -> + Mint.HTTP.close(conn) + failed(state, :socket_error) + end + end + + def handle_info({:connector, pid, {:error, reason}}, %{connector: pid} = state), + do: failed(state, reason) + + def handle_info(message, %{conn: conn} = state) when conn != nil do + case WS.stream(conn, message) do + {:ok, conn, responses} -> + responses(%{state | conn: conn}, responses) + + {:error, conn, %Mint.TransportError{reason: :closed}, _} -> + failed(%{state | conn: conn}, :connection_closed) + + {:error, conn, _, _} -> + failed(%{state | conn: conn}, :socket_error) + + :unknown -> + {:noreply, state} + end + end + + def handle_info(_message, state), do: {:noreply, state} + + @impl true + def terminate(_reason, state) do + if state.connector, do: Process.exit(state.connector, :kill) + + if state.conn do + _ = send_frames(state, [{:close, 1000, ""}]) + Mint.HTTP.close(state.conn) + end + + if state.owner_alive, do: send(state.owner, {__MODULE__, self(), :closed}) + :ok + end + + defp failed(state, reason) do + notify!(state, {:error, reason}) + {:stop, :normal, state} + end + + defp responses(state, []), do: {:noreply, state} + + defp responses(%{ref: ref} = state, [{:data, ref, data} | rest]) do + case WS.decode(state.ws, data) do + {:ok, ws, frames} -> + case frames(%{state | ws: ws}, frames) do + {:ok, state} -> responses(state, rest) + {:error, reason, state} -> failed(state, reason) + end + + {:error, ws, _} -> + failed(%{state | ws: ws}, :invalid_frame) + end + end + + defp responses(%{ref: ref} = state, [{:done, ref} | _]), do: failed(state, :connection_closed) + defp responses(state, [_ | rest]), do: responses(state, rest) + + defp frames(state, []), do: {:ok, state} + + defp frames(state, [{:ping, data} | rest]) do + with {:ok, state} <- send_frames(state, [{:pong, data}]), do: frames(state, rest) + end + + defp frames(state, [{:pong, _} | rest]), do: frames(state, rest) + defp frames(state, [{:close, _, _} | _]), do: {:error, :connection_closed, state} + + defp frames(state, [{kind, _} = frame | rest]) when kind in [:text, :binary] do + with {:ok, events, outgoing, adapter} <- state.module.handle_frame(frame, state.adapter), + {:ok, state} <- send_frames(%{state | adapter: adapter}, outgoing), + {:ok, state} <- events(state, events) do + frames(state, rest) + else + {:error, reason, state} -> {:error, reason, state} + {:error, reason} -> {:error, reason, state} + end + end + + defp frames(state, _), do: {:error, :invalid_frame, state} + + defp events(state, []), do: {:ok, state} + + defp events(%{phase: :open} = state, [:ready | rest]) do + :erlang.cancel_timer(state.connect_timer) + state = restart_idle(%{state | phase: :ready, connect_timer: nil}) + with :ok <- notify(state, :ready), do: events(state, rest) + end + + defp events(state, [{:audio, %Audio{} = audio} = event | rest]) do + state = %{state | received: state.received + div(byte_size(audio.data), 2)} + with :ok <- notify(state, event), do: events(state, rest) + end + + defp events(state, [{:text, text} = event | rest]) when is_binary(text) do + with :ok <- notify(state, event), do: events(state, rest) + end + + defp events(state, _), do: {:error, :invalid_event, state} + + defp notify(state, event) do + case Process.info(state.owner, :message_queue_len) do + {:message_queue_len, length} when length >= state.max_queue -> + {:error, :owner_overloaded, state} + + _ -> + send(state.owner, {__MODULE__, self(), event}) + :ok + end + end + + defp notify!(state, event), do: send(state.owner, {__MODULE__, self(), event}) + + defp restart_idle(state) do + if state.idle_timer, do: :erlang.cancel_timer(state.idle_timer) + %{state | idle_timer: :erlang.start_timer(state.idle_ms, self(), :idle)} + end + + defp send_frames(state, frames) do + Enum.reduce_while(frames, {:ok, state}, fn frame, {:ok, state} -> + result = + case WS.encode(state.ws, frame) do + {:ok, ws, data} -> write(%{state | ws: ws}, data) + {:error, ws, _} -> {:error, :send_failed, %{state | ws: ws}} + end + + if match?({:ok, _}, result), do: {:cont, result}, else: {:halt, result} + end) + end + + defp write(state, data) do + case WS.stream_request_body(state.conn, state.ref, data) do + {:ok, conn} -> + {:ok, %{state | conn: conn}} + + {:error, conn, %Mint.TransportError{reason: reason}} + when reason in [:closed, :epipe, :econnreset] -> + {:error, :connection_closed, %{state | conn: conn}} + + {:error, conn, _} -> + {:error, :send_failed, %{state | conn: conn}} + end + end + + # Runs in a linked process, so the session answers calls while it connects. + # The socket moves to the session after the WebSocket upgrade. + defp connect(server, config, timeout, send_timeout) do + deadline = System.monotonic_time(:millisecond) + timeout + transport = [send_timeout: send_timeout, send_timeout_close: true] + + case Socket.open(config.url, config.headers, deadline, + mode: :active, + transport_opts: transport + ) do + {:ok, conn, ws, ref, pending} -> + case Mint.HTTP.controlling_process(conn, server) do + {:ok, conn} -> + {:ok, conn, ws, ref, pending} + + {:error, _} -> + Mint.HTTP.close(conn) + {:error, :connect_failed} + end + + {:error, :timeout} -> + {:error, :connect_timeout} + + {:error, {:http_status, _}} = error -> + error + + {:error, _} -> + {:error, :connect_failed} + end + end +end diff --git a/lib/audio_flow/duplex/adapter.ex b/lib/audio_flow/duplex/adapter.ex new file mode 100644 index 0000000..8795aa4 --- /dev/null +++ b/lib/audio_flow/duplex/adapter.ex @@ -0,0 +1,41 @@ +defmodule AudioFlow.Duplex.Adapter do + @moduledoc """ + Wire protocol of one continuous `AudioFlow.Duplex` model connection. + + `AudioFlow.Duplex` owns the WebSocket, the timers, the bounds and the owner + messages. An adapter only maps audio to frames and frames to events. All + callbacks except `config/1` run in the session process. + + `handle_frame/2` returns events in wire order: + + * `:ready` once, after the model handshake. The session rejects audio + until then. + * `{:audio, %AudioFlow.Audio{}}` with model output at `:sample_rate`. + * `{:text, text}` with model text. + """ + alias AudioFlow.Audio + + @type frame :: {:text | :binary, binary()} + @type event :: :ready | {:audio, Audio.t()} | {:text, String.t()} + + @doc """ + Validates options in the caller of `AudioFlow.Duplex.start_link/1`. Raises + `ArgumentError` for invalid options. `:url` must be `ws` or `wss`. + """ + @callback config(options :: keyword()) :: %{ + url: String.t(), + headers: [{String.t(), String.t()}], + sample_rate: pos_integer(), + options: term() + } + + @doc "Returns the initial protocol state from `config/1` `:options`." + @callback init(options :: term()) :: state :: term() + + @callback handle_frame(frame(), state :: term()) :: + {:ok, [event()], [frame()], state :: term()} | {:error, term()} + + @doc "Maps one accepted input chunk to frames. Partial model frames may stay buffered." + @callback handle_audio(Audio.t(), state :: term()) :: + {:ok, [frame()], state :: term()} | {:error, term()} +end diff --git a/lib_media/audio_flow/adapters/moshi.ex b/lib_media/audio_flow/adapters/moshi.ex index 85cffb0..4b50f34 100644 --- a/lib_media/audio_flow/adapters/moshi.ex +++ b/lib_media/audio_flow/adapters/moshi.ex @@ -8,8 +8,10 @@ defmodule AudioFlow.Adapters.Moshi do Moshi does not transcribe the user, so there is no `:transcript` event. Use directly or in Session `:speech_to_speech`; see docs/providers.md. - Moshi is full duplex and has no end-of-turn signal. The adapter sends the - committed input, then silence, one 80 ms frame for each frame it receives. + Moshi is full duplex and has no end-of-turn signal. For continuous microphone + input with simultaneous output, use `AudioFlow.Duplex` with + `AudioFlow.Duplex.Moshi` instead. This adapter sends the committed input, + then silence, one 80 ms frame for each frame it receives. Output that belongs to the input period is dropped. The reply ends after `:end_silence_ms` of model output without text, or fails with `:no_reply` when `:max_reply_ms` passes without text. diff --git a/lib_media/audio_flow/duplex/moshi.ex b/lib_media/audio_flow/duplex/moshi.ex new file mode 100644 index 0000000..7a857c0 --- /dev/null +++ b/lib_media/audio_flow/duplex/moshi.ex @@ -0,0 +1,80 @@ +defmodule AudioFlow.Duplex.Moshi do + @moduledoc """ + `AudioFlow.Duplex` adapter for a local Kyutai Moshi server + (`moshi_mlx.local_web` or the PyTorch `moshi.server`). Requires + `AUDIOFLOW_MEDIA=1` for Ogg Opus. + + Input is mono s16le PCM at 24 kHz. The adapter sends each complete 80 ms + frame (1,920 samples, 3,840 bytes) as one Ogg page of four 20 ms Opus + packets. A shorter remainder waits for the next push. Push 3,840-byte chunks + to send each frame at once. + + The session emits all decoded model audio and every text token as it + arrives, also while input continues. Moshi does not transcribe the user. + + Option: `:endpoint` (`"ws://127.0.0.1:8998/api/chat"`). + """ + @behaviour AudioFlow.Duplex.Adapter + alias AudioFlow.Audio + alias AudioFlow.Moshi.Codec + + @endpoint "ws://127.0.0.1:8998/api/chat" + + @impl true + def config(options) do + options = Keyword.validate!(options, endpoint: @endpoint) + endpoint = options[:endpoint] + + unless is_binary(endpoint), do: raise(ArgumentError, "endpoint must be a string") + + %{url: endpoint, headers: [], sample_rate: Codec.rate(), options: []} + end + + @impl true + def init([]), do: %{codec: Codec.new(), ready: false, pending: <<>>} + + @impl true + def handle_frame(frame, state) do + case {Codec.wire(frame), state.ready} do + {{:ok, :ready}, false} -> + {codec, headers} = Codec.headers(state.codec) + {:ok, [:ready], [headers], %{state | codec: codec, ready: true}} + + {{:ok, {:text, text}}, true} -> + {:ok, [{:text, text}], [], state} + + {{:ok, {:audio, data}}, true} -> + case Codec.decode(state.codec, data) do + {:ok, codec, <<>>} -> {:ok, [], [], %{state | codec: codec}} + {:ok, codec, pcm} -> {:ok, [audio(pcm)], [], %{state | codec: codec}} + :error -> {:error, :invalid_audio} + end + + _ -> + {:error, :invalid_event} + end + end + + @impl true + def handle_audio(%Audio{data: data}, state) do + size = Codec.frame_samples() * 2 + {frames, pending} = split(state.pending <> data, size, []) + + {codec, pages} = + Enum.reduce(frames, {state.codec, []}, fn pcm, {codec, pages} -> + {codec, page} = Codec.encode(codec, pcm) + {codec, [page | pages]} + end) + + {:ok, Enum.reverse(pages), %{state | codec: codec, pending: pending}} + end + + defp split(pcm, size, frames) when byte_size(pcm) < size, do: {Enum.reverse(frames), pcm} + + defp split(pcm, size, frames) do + <> = pcm + split(rest, size, [frame | frames]) + end + + defp audio(pcm), do: {:audio, %Audio{data: pcm, sample_rate: Codec.rate()}} +end diff --git a/test/duplex_test.exs b/test/duplex_test.exs new file mode 100644 index 0000000..1c5eb21 --- /dev/null +++ b/test/duplex_test.exs @@ -0,0 +1,256 @@ +if System.get_env("AUDIOFLOW_MEDIA") == "1" do + defmodule AudioFlow.DuplexTest do + use ExUnit.Case, async: true + alias AudioFlow.Audio + alias AudioFlow.Duplex + alias AudioFlow.Test.MoshiServer + + # One Moshi step: 80 ms of 24 kHz mono s16le. + @frame_bytes 3_840 + + defp tone(bytes) do + for i <- 0..(div(bytes, 2) - 1), + into: <<>>, + do: <> + end + + defp chunk(bytes \\ @frame_bytes), do: %Audio{data: tone(bytes), sample_rate: 24_000} + + defp start(server_options, options \\ []) do + endpoint = MoshiServer.endpoint(self(), server_options) + + {:ok, duplex} = + Duplex.start_link([owner: self(), adapter: {Duplex.Moshi, endpoint: endpoint}] ++ options) + + assert_receive {:moshi_server, server} + {duplex, server} + end + + defp ready(server_options \\ [], options \\ []) do + {duplex, server} = start(server_options, options) + assert_receive {Duplex, ^duplex, :ready} + # The Ogg Opus head and tags pages carry no PCM. + assert_receive {:client_pcm, <<>>} + {duplex, server} + end + + defp drain(duplex, events) do + receive do + {Duplex, ^duplex, event} -> drain(duplex, [event | events]) + after + 0 -> events + end + end + + test "model audio and text arrive while microphone input continues" do + {duplex, _server} = ready(script: %{1 => " Hi"}) + + for index <- 0..2 do + assert :ok = Duplex.push(duplex, chunk()) + assert_receive {:client_pcm, pcm} + assert byte_size(pcm) == @frame_bytes + assert pcm |> :binary.bin_to_list() |> Enum.any?(&(&1 != 0)) + + # Each input frame is answered before the next one is pushed: no + # end-of-turn gate holds output back while the user speaks. + assert_receive {Duplex, ^duplex, {:audio, %Audio{data: out, sample_rate: 24_000}}} + assert byte_size(out) == @frame_bytes + if index == 1, do: assert_receive({Duplex, ^duplex, {:text, " Hi"}}) + end + + refute_received {Duplex, ^duplex, {:error, _}} + end + + test "sends each complete 80 ms frame as its own message and keeps the remainder" do + {duplex, _server} = ready() + + assert :ok = Duplex.push(duplex, chunk(1_000)) + refute_receive {:client_pcm, _}, 100 + + assert :ok = Duplex.push(duplex, chunk(2 * @frame_bytes - 1_000)) + assert_receive {:client_pcm, first} + assert_receive {:client_pcm, second} + assert byte_size(first) == @frame_bytes and byte_size(second) == @frame_bytes + end + + test "emits ready only after the model handshake and rejects audio before it" do + {duplex, server} = start(handshake: :manual) + + assert {:error, :not_ready} = Duplex.push(duplex, chunk()) + refute_receive {Duplex, ^duplex, :ready}, 100 + + send(server, :handshake) + assert_receive {Duplex, ^duplex, :ready} + assert :ok = Duplex.push(duplex, chunk()) + end + + test "bounds unanswered input and rejects invalid chunks without closing" do + {duplex, server} = + ready([reply: :manual], max_input_lead_ms: 200, max_chunk_bytes: @frame_bytes) + + assert {:error, :invalid_audio} = + Duplex.push(duplex, %Audio{data: tone(@frame_bytes), sample_rate: 16_000}) + + assert {:error, :invalid_audio} = + Duplex.push(duplex, %Audio{data: <<0>>, sample_rate: 24_000}) + + assert {:error, :too_large} = Duplex.push(duplex, chunk(2 * @frame_bytes)) + + # 200 ms bound: two 80 ms frames fit, a third does not. + assert :ok = Duplex.push(duplex, chunk()) + assert :ok = Duplex.push(duplex, chunk()) + assert {:error, :overloaded} = Duplex.push(duplex, chunk()) + assert_receive {:client_pcm, _} + assert_receive {:client_pcm, _} + refute_receive {:client_pcm, _}, 100 + + send(server, :reply) + assert_receive {Duplex, ^duplex, {:audio, _}} + assert_receive {Duplex, ^duplex, {:audio, _}} + assert :ok = Duplex.push(duplex, chunk()) + assert_receive {:client_pcm, _} + refute_received {Duplex, ^duplex, {:error, _}} + end + + test "stop closes the connection and later calls report it closed" do + {duplex, _server} = ready() + + assert :ok = Duplex.stop(duplex) + assert_receive {Duplex, ^duplex, :closed} + assert_receive :moshi_server_closed + refute_received {Duplex, ^duplex, {:error, _}} + assert {:error, :closed} = Duplex.push(duplex, chunk()) + assert :ok = Duplex.stop(duplex) + end + + test "owner exit closes the connection" do + owner = spawn(fn -> Process.sleep(:infinity) end) + endpoint = MoshiServer.endpoint(self()) + + {:ok, duplex} = + Duplex.start_link(owner: owner, adapter: {Duplex.Moshi, endpoint: endpoint}) + + ref = Process.monitor(duplex) + assert_receive {:moshi_server, _server} + Process.exit(owner, :kill) + + assert_receive {:DOWN, ^ref, :process, ^duplex, :normal} + assert_receive :moshi_server_closed + end + + test "fails the session when the owner mailbox is full" do + test = self() + + owner = + spawn(fn -> + receive do + {Duplex, _, :ready} = message -> send(test, message) + end + + Process.sleep(:infinity) + end) + + endpoint = MoshiServer.endpoint(self()) + + {:ok, duplex} = + Duplex.start_link( + owner: owner, + adapter: {Duplex.Moshi, endpoint: endpoint}, + max_owner_queue: 1 + ) + + ref = Process.monitor(duplex) + assert_receive {Duplex, ^duplex, :ready} + assert :ok = Duplex.push(duplex, chunk(2 * @frame_bytes)) + + assert_receive {:DOWN, ^ref, :process, ^duplex, :normal} + assert_receive :moshi_server_closed + + assert {:messages, + [ + {Duplex, ^duplex, {:audio, _}}, + {Duplex, ^duplex, {:error, :owner_overloaded}}, + {Duplex, ^duplex, :closed} + ]} = Process.info(owner, :messages) + + Process.exit(owner, :kill) + end + + for {reason, server_options, options, action} <- [ + {:connect_timeout, [handshake: :manual], [connect_timeout_ms: 100], nil}, + {:idle_timeout, [], [idle_timeout_ms: 100], nil}, + {:session_timeout, [], [max_session_ms: 150], nil}, + {:connection_closed, [], [], :close} + ] do + test "reports #{reason}, then closed, and closes the connection" do + {duplex, server} = start(unquote(server_options), unquote(options)) + ref = Process.monitor(duplex) + if unquote(action), do: send(server, unquote(action)) + + assert_receive {Duplex, ^duplex, {:error, unquote(reason)}}, 1_000 + assert_receive {Duplex, ^duplex, :closed} + assert_receive :moshi_server_closed + assert_receive {:DOWN, ^ref, :process, ^duplex, :normal} + end + end + + test "reports connect_failed when no server listens" do + {:ok, socket} = :gen_tcp.listen(0, ip: {127, 0, 0, 1}) + {:ok, port} = :inet.port(socket) + :ok = :gen_tcp.close(socket) + + {:ok, duplex} = + Duplex.start_link( + owner: self(), + adapter: {Duplex.Moshi, endpoint: "ws://127.0.0.1:#{port}/api/chat"} + ) + + assert_receive {Duplex, ^duplex, {:error, :connect_failed}} + assert_receive {Duplex, ^duplex, :closed} + end + + test "rejects invalid options in the caller" do + adapter = {Duplex.Moshi, endpoint: "http://127.0.0.1:8998/api/chat"} + + assert_raise ArgumentError, fn -> Duplex.start_link(owner: self(), adapter: adapter) end + + assert_raise ArgumentError, fn -> + Duplex.start_link(owner: self(), adapter: {Duplex.Moshi, port: 8998}) + end + end + + @tag :http_model + test "a local Moshi server answers continuous input" do + endpoint = System.get_env("AUDIOFLOW_MOSHI_ENDPOINT", "ws://127.0.0.1:8998/api/chat") + question = System.fetch_env!("AUDIOFLOW_MOSHI_PCM") |> File.read!() + + {:ok, duplex} = + Duplex.start_link( + owner: self(), + adapter: {Duplex.Moshi, endpoint: endpoint}, + connect_timeout_ms: 60_000 + ) + + assert_receive {Duplex, ^duplex, :ready}, 60_000 + silence = :binary.copy(<<0>>, @frame_bytes * 75) + + events = + for < silence>>, reduce: [] do + events -> + # The first steps after server start are slow; those pushes overload. + assert Duplex.push(duplex, %Audio{data: frame, sample_rate: 24_000}) in [ + :ok, + {:error, :overloaded} + ] + + Process.sleep(80) + drain(duplex, events) + end + + assert Enum.any?(events, &match?({:audio, _}, &1)) + assert Enum.any?(events, &match?({:text, _}, &1)) + refute Enum.any?(events, &match?({:error, _}, &1)) + Duplex.stop(duplex) + end + end +end From fbbd6d7f92a57369320d6da1aeb9de78b65adc1b Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 22:45:23 +0200 Subject: [PATCH 07/12] fix(duplex): contain invalid audio failures and bound responses --- docs/providers.md | 8 +++++ lib/audio_flow/duplex.ex | 53 +++++++++++++++++++++++------ lib_media/audio_flow/moshi/codec.ex | 9 +++-- test/duplex_test.exs | 27 +++++++++++++++ test/support/moshi_server.ex | 1 + 5 files changed, 85 insertions(+), 13 deletions(-) diff --git a/docs/providers.md b/docs/providers.md index 5bfd123..57d0525 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -216,6 +216,11 @@ handshake), `{:audio, %AudioFlow.Audio{}}`, `{:text, token}`, after the session stops. Keep the endpoint in server configuration; the browser does not need it. +`start/1` starts an unlinked session with the same API. Use it when the owner +must also survive an unexpected adapter crash, as the chat UI does. Monitor +the returned process to detect these crashes. Both start functions monitor +the owner and close the connection when it exits. + The adapter sends each complete 80 ms frame (3,840 bytes at 24 kHz) as one Ogg page at once. A shorter remainder waits for the next push. Moshi answers each input frame with one output frame, so the client must push continuous audio, @@ -227,6 +232,9 @@ Bounds (defaults): - `:idle_timeout_ms` (30,000) without an accepted push. - `:max_session_ms` (1,800,000) in total. - `:max_chunk_bytes` (48,000) for each push, else `{:error, :too_large}`. +- `:max_response_bytes` (67,108,864) for all incoming WebSocket bytes in a + session, including fragments. The session fails with `:response_too_large` + at this bound. Incomplete Ogg packets are limited to 256 KiB. - `:max_input_lead_ms` (2,000) of pushed audio that model audio has not answered. A push past it returns `{:error, :overloaded}` and is not sent, for example while MLX warms up. diff --git a/lib/audio_flow/duplex.ex b/lib/audio_flow/duplex.ex index 106c4d7..0c8e459 100644 --- a/lib/audio_flow/duplex.ex +++ b/lib/audio_flow/duplex.ex @@ -18,6 +18,11 @@ defmodule AudioFlow.Duplex do ], max_session_ms: [type: :pos_integer, default: 1_800_000, doc: "Total session time."], max_chunk_bytes: [type: :pos_integer, default: 48_000, doc: "Largest push."], + max_response_bytes: [ + type: :pos_integer, + default: 67_108_864, + doc: "Total incoming WebSocket bytes, including partial frames." + ], max_input_lead_ms: [ type: :pos_integer, default: 2_000, @@ -81,7 +86,12 @@ defmodule AudioFlow.Duplex do @call_timeout 5_000 @doc "Starts a session. Raises `ArgumentError` for invalid options." - def start_link(options) do + def start_link(options), do: start_session(options, :linked) + + @doc "Starts an unlinked session. The session still monitors its owner." + def start(options), do: start_session(options, :unlinked) + + defp start_session(options, link) do options = NimbleOptions.validate!(options, @schema) owner = options[:owner] @@ -91,7 +101,11 @@ defmodule AudioFlow.Duplex do Code.ensure_loaded!(module) config = module.config(adapter_options) Socket.endpoint!(config.url) - GenServer.start_link(__MODULE__, {options, module, config}) + args = {options, module, config} + + if link == :linked, + do: GenServer.start_link(__MODULE__, args), + else: GenServer.start(__MODULE__, args) end @doc """ @@ -147,6 +161,8 @@ defmodule AudioFlow.Duplex do ref: nil, pushed: 0, received: 0, + response_bytes: 0, + max_response_bytes: options[:max_response_bytes], max_lead: lead, max_chunk: options[:max_chunk_bytes], max_queue: options[:max_owner_queue], @@ -180,13 +196,18 @@ defmodule AudioFlow.Duplex do end defp check_audio(%Audio{} = audio, state) do - samples = div(byte_size(audio.data), 2) - cond do - not Audio.valid?(audio) or audio.sample_rate != state.rate -> {:error, :invalid_audio} - byte_size(audio.data) > state.max_chunk -> {:error, :too_large} - state.pushed + samples - state.received > state.max_lead -> {:error, :overloaded} - true -> :ok + not Audio.valid?(audio) or audio.sample_rate != state.rate -> + {:error, :invalid_audio} + + byte_size(audio.data) > state.max_chunk -> + {:error, :too_large} + + state.pushed + div(byte_size(audio.data), 2) - state.received > state.max_lead -> + {:error, :overloaded} + + true -> + :ok end end @@ -270,6 +291,19 @@ defmodule AudioFlow.Duplex do defp responses(state, []), do: {:noreply, state} defp responses(%{ref: ref} = state, [{:data, ref, data} | rest]) do + bytes = state.response_bytes + byte_size(data) + + if bytes > state.max_response_bytes do + failed(state, :response_too_large) + else + decode_response(%{state | response_bytes: bytes}, data, rest) + end + end + + defp responses(%{ref: ref} = state, [{:done, ref} | _]), do: failed(state, :connection_closed) + defp responses(state, [_ | rest]), do: responses(state, rest) + + defp decode_response(state, data, rest) do case WS.decode(state.ws, data) do {:ok, ws, frames} -> case frames(%{state | ws: ws}, frames) do @@ -282,9 +316,6 @@ defmodule AudioFlow.Duplex do end end - defp responses(%{ref: ref} = state, [{:done, ref} | _]), do: failed(state, :connection_closed) - defp responses(state, [_ | rest]), do: responses(state, rest) - defp frames(state, []), do: {:ok, state} defp frames(state, [{:ping, data} | rest]) do diff --git a/lib_media/audio_flow/moshi/codec.ex b/lib_media/audio_flow/moshi/codec.ex index 5ef74b8..9149871 100644 --- a/lib_media/audio_flow/moshi/codec.ex +++ b/lib_media/audio_flow/moshi/codec.ex @@ -17,6 +17,7 @@ defmodule AudioFlow.Moshi.Codec do @application 2049 @bitrate -1000 @signal 3001 + @max_pending_bytes 262_144 def rate, do: @rate def frame_samples, do: @frame @@ -74,10 +75,14 @@ defmodule AudioFlow.Moshi.Codec do Decoder.decode_packet(codec.decoder, packet) end - {:ok, %{codec | buffer: rest, continued: continued}, pcm} + if byte_size(rest) + byte_size(continued || <<>>) > @max_pending_bytes do + :error + else + {:ok, %{codec | buffer: rest, continued: continued}, pcm} + end rescue # Parser.parse/2 raises on a corrupt page. - RuntimeError -> :error + _error in [RuntimeError, ErlangError] -> :error end defp opus_header?(<<"OpusHead", _::binary>>), do: true diff --git a/test/duplex_test.exs b/test/duplex_test.exs index 1c5eb21..1e8b046 100644 --- a/test/duplex_test.exs +++ b/test/duplex_test.exs @@ -4,6 +4,7 @@ if System.get_env("AUDIOFLOW_MEDIA") == "1" do alias AudioFlow.Audio alias AudioFlow.Duplex alias AudioFlow.Test.MoshiServer + alias Membrane.Ogg.Page # One Moshi step: 80 ms of 24 kHz mono s16le. @frame_bytes 3_840 @@ -88,6 +89,9 @@ if System.get_env("AUDIOFLOW_MEDIA") == "1" do {duplex, server} = ready([reply: :manual], max_input_lead_ms: 200, max_chunk_bytes: @frame_bytes) + assert {:error, :invalid_audio} = + Duplex.push(duplex, %Audio{data: nil, sample_rate: 24_000}) + assert {:error, :invalid_audio} = Duplex.push(duplex, %Audio{data: tone(@frame_bytes), sample_rate: 16_000}) @@ -123,6 +127,29 @@ if System.get_env("AUDIOFLOW_MEDIA") == "1" do assert :ok = Duplex.stop(duplex) end + test "corrupt Opus is reported as an error without crashing the owner" do + {duplex, server} = ready() + ref = Process.monitor(duplex) + + page = + Page.create_first(2) + |> Page.append_packet!(<<3>>) + |> Page.finalize(0) + |> Page.serialize() + + send(server, {:push, [{:binary, <<1>> <> page}]}) + assert_receive {Duplex, ^duplex, {:error, :invalid_audio}} + assert_receive {Duplex, ^duplex, :closed} + assert_receive {:DOWN, ^ref, :process, ^duplex, :normal} + end + + test "the incoming byte budget closes the connection" do + {duplex, _server} = start([], max_response_bytes: 1) + assert_receive {Duplex, ^duplex, {:error, :response_too_large}} + assert_receive {Duplex, ^duplex, :closed} + assert_receive :moshi_server_closed + end + test "owner exit closes the connection" do owner = spawn(fn -> Process.sleep(:infinity) end) endpoint = MoshiServer.endpoint(self()) diff --git a/test/support/moshi_server.ex b/test/support/moshi_server.ex index 2fb4f3e..0ec5e44 100644 --- a/test/support/moshi_server.ex +++ b/test/support/moshi_server.ex @@ -95,6 +95,7 @@ if Code.ensure_loaded?(Membrane.Ogg.Parser) do def handle_info(:handshake, state), do: {:push, handshake(), state} def handle_info(:reply, state), do: answer(state) def handle_info(:close, state), do: {:stop, :normal, state} + def handle_info({:push, frames}, state), do: {:push, frames, state} @impl true def terminate(_reason, state) do From a5d9c7df33a25d39420678b3189de94a4353dcba Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 22:45:33 +0200 Subject: [PATCH 08/12] fix(chat): clarify duplex controls and preserve early handshakes --- examples/chat/assets/js/duplex.js | 10 ++- examples/chat/assets/test/duplex.test.js | 14 +++- examples/chat/lib/chat_web/live/chat_live.ex | 71 +++++++++++--------- examples/chat/test/duplex_test.exs | 5 +- 4 files changed, 60 insertions(+), 40 deletions(-) diff --git a/examples/chat/assets/js/duplex.js b/examples/chat/assets/js/duplex.js index 9491ed5..d7166fe 100644 --- a/examples/chat/assets/js/duplex.js +++ b/examples/chat/assets/js/duplex.js @@ -76,15 +76,18 @@ export class Chunker { export const Duplex = { mounted() { this.call = null; + this.readyGeneration = null; + this.controls = this.el.parentElement; this.onClick = (event) => { const button = event.target.closest("[data-call]"); if (!button || button.disabled) return; if (button.dataset.call === "start") this.start(); else this.stop(); }; - this.el.addEventListener("click", this.onClick); + this.controls.addEventListener("click", this.onClick); this.handleEvent("call_ready", ({ generation }) => { + this.readyGeneration = generation; const call = this.current(generation); if (call) call.ready = true; }); @@ -99,7 +102,7 @@ export const Duplex = { }, destroyed() { - this.el.removeEventListener("click", this.onClick); + this.controls.removeEventListener("click", this.onClick); this.release(this.call); }, @@ -172,6 +175,7 @@ export const Duplex = { } if (!reply?.ok) return this.release(call); call.generation = reply.generation; + call.ready = this.readyGeneration === reply.generation; this.ticker = setInterval(() => this.draw(), 500); this.draw(); }); @@ -268,7 +272,7 @@ export const Duplex = { }, draw(text) { - const stats = this.el.querySelector("#duplex-stats"); + const stats = this.controls.querySelector("#duplex-stats"); if (!stats) return; const call = this.call; if (text !== undefined || !call) { diff --git a/examples/chat/assets/test/duplex.test.js b/examples/chat/assets/test/duplex.test.js index b0d983b..4f83c60 100644 --- a/examples/chat/assets/test/duplex.test.js +++ b/examples/chat/assets/test/duplex.test.js @@ -92,7 +92,7 @@ function mount() { }; const hook = { ...Duplex, - el, + el: { parentElement: el }, handleEvent(name, fn) { handlers[name] = fn; }, @@ -172,6 +172,18 @@ test("input waits for acknowledgements and drops the oldest chunks past the queu assert.match(view.stats.textContent, /Sent 1 · dropped 4 input chunks/); }); +test("capture starts when the model handshake arrives before the start reply", async () => { + const view = mount(); + grantMicrophone(); + view.click("start"); + await tick(); + view.handlers.call_ready({ generation: 9 }); + view.sent("call_start")[0].reply({ ok: true, generation: 9 }); + speak(30); + assert.equal(view.sent("call_audio").length, 1); + assert.equal(view.sent("call_audio")[0].payload.generation, 9); +}); + test("model audio plays while the microphone keeps sending", async () => { const view = await connect(); const [context] = contexts.slice(-1); diff --git a/examples/chat/lib/chat_web/live/chat_live.ex b/examples/chat/lib/chat_web/live/chat_live.ex index adf8c95..24c7d45 100644 --- a/examples/chat/lib/chat_web/live/chat_live.ex +++ b/examples/chat/lib/chat_web/live/chat_live.ex @@ -378,9 +378,9 @@ defmodule ChatWeb.ChatLive do end end - # Duplex.start_link/1 raises for options that it cannot use. + # A model failure must not stop the LiveView. Duplex monitors this owner. defp start_duplex(adapter) do - Duplex.start_link(owner: self(), adapter: adapter) + Duplex.start(owner: self(), adapter: adapter) rescue error in ArgumentError -> {:error, Exception.message(error)} end @@ -836,7 +836,9 @@ defmodule ChatWeb.ChatLive do else: "Type a message, or record one with the microphone."}

- New chat + + {if @duplex, do: "Clear text", else: "New chat"} +
@@ -849,7 +851,7 @@ defmodule ChatWeb.ChatLive do > {label} -
- +
+ + + + + + Apply + +
+
-

- - ≈ {gb(@models.memory_gb)} GB of model weights{if @system_memory_gb, - do: " · #{gb(@system_memory_gb)} GB memory"} - - {fit_text(@system_memory_gb)} -

-
+
+
Start conversation @@ -977,15 +1054,41 @@ defmodule ChatWeb.ChatLive do
{call_label(@call_status)} -
-

- Use headphones. Clear text does not reset Moshi. Its context stays until the model service restarts. -

+
+ Diagnostics + +
+
+ Settings +
+

+ ≈ {gb(@models.memory_gb)} GB of model weights{if @system_memory_gb, + do: " · #{gb(@system_memory_gb)} GB memory"}. {fit_text(@system_memory_gb)} +

+
+ + {if @capture, do: "Delete saved transcripts", else: "Save redacted transcripts"} + + + Text only, with all words replaced by [REDACTED]. Deleted when you leave. + +
+
+ {id} + + Download + + + Delete + +
+
+

No messages yet. @@ -1018,12 +1121,19 @@ defmodule ChatWeb.ChatLive do -

- - - - {if @paused, do: "Web Audio suspended", else: "Playback running or awaiting endpoint"} -
+
+ Diagnostics +
+ + Pause playback + + + Resume + + Confirm stop + Playback acknowledged: {@played_ms} ms +
+
nil end) assert missing =~ "DEEPGRAM_API_KEY" assert missing =~ "ELEVENLABS_VOICE_ID" - for {mode, rate, adapter} <- [ - {"openai", 24_000, AudioFlow.Adapters.OpenAIRealtime}, - {"gemini", 16_000, AudioFlow.Adapters.GeminiLive} + gemini = Map.put(settings, "mode", "gemini") + assert Chat.Setup.rate(gemini) == 16_000 + assert {:ok, opts} = Chat.Setup.options(gemini, fn _ -> "server-value" end) + assert {AudioFlow.Adapters.GeminiLive, provider} = opts[:speech_to_speech] + assert is_function(provider[:api_key], 0) + refute Keyword.has_key?(opts, :history) + refute Keyword.has_key?(opts, :stt) + + # OpenAI is an always-on conversation; the key stays a server-side function. + openai = %{settings | "mode" => "openai", "voice" => "cedar"} + assert Chat.Setup.rate(openai) == 24_000 + assert Chat.Setup.duplex?(openai) + env = &%{"OPENAI_API_KEY" => "server-key", "OPENAI_REALTIME_MODEL" => "gpt-realtime"}[&1] + + assert {:ok, [duplex: {AudioFlow.Duplex.OpenAIRealtime, provider}]} = + Chat.Setup.options(openai, env) + + assert provider[:model] == "gpt-realtime" and provider[:voice] == "cedar" + assert provider[:api_key].() == "server-key" + refute Keyword.has_key?(provider, :endpoint) + + for {endpoint, result} <- [ + {"ws://127.0.0.1:9000/v1/realtime", :ok}, + {"https://api.openai.com/v1/realtime", :error}, + {"wss://user:secret@proxy.test/v1/realtime", :error} ] do - s = Map.put(settings, "mode", mode) - assert Chat.Setup.rate(s) == rate - assert {:ok, opts} = Chat.Setup.options(s, fn _ -> "server-value" end) - assert {^adapter, provider} = opts[:speech_to_speech] - assert is_function(provider[:api_key], 0) - refute Keyword.has_key?(opts, :history) - refute Keyword.has_key?(opts, :stt) + env = &(%{"OPENAI_REALTIME_ENDPOINT" => endpoint}[&1] || env.(&1)) + assert elem(Chat.Setup.options(openai, env), 0) == result end + + assert {:error, missing} = Chat.Setup.options(openai, fn _ -> nil end) + assert missing =~ "OPENAI_API_KEY" end test "recording redacts split text, omits PCM and deletes the private directory" do @@ -91,12 +111,11 @@ defmodule ChatTest do test "actual LiveView controls submit, configure, record, download and delete" do {:ok, view, html} = live(build_conn(), "/") assert html =~ "Synthetic demo" - assert html =~ "No inference" view |> element("#configuration") |> render_submit(%{"mode" => "remote"}) assert render(view) =~ "Missing server environment" - assert render(view) =~ "Active: demo" + assert has_element?(view, "select[name=mode] option[value=demo][selected]") view |> element("button[phx-click=capture]") |> render_click() - assert render(view) =~ "Disable and delete recordings" + assert render(view) =~ "Delete saved transcripts" render_hook(view, "send", %{"text" => "private-message"}) assert eventually(fn -> diff --git a/examples/chat/test/duplex_test.exs b/examples/chat/test/duplex_test.exs index 7894df5..59ee40e 100644 --- a/examples/chat/test/duplex_test.exs +++ b/examples/chat/test/duplex_test.exs @@ -165,7 +165,6 @@ if Code.ensure_loaded?(AudioFlow.Duplex.Moshi) do html = render(view) assert html =~ "Start conversation" assert html =~ "Not connected" - assert html =~ "AudioFlow sends your microphone audio to local Moshi" refute has_element?(view, "#prompt") refute has_element?(view, "#recorder") assert has_element?(view, "button[data-call=stop][disabled]") @@ -176,7 +175,7 @@ if Code.ensure_loaded?(AudioFlow.Duplex.Moshi) do moshi(%{0 => " Hi", 1 => " there."}) {:ok, view, _} = live(build_conn(), "/") generation = connect(view) - assert render(view) =~ "Live: microphone and playback on" + assert render(view) =~ "Live · microphone on" assert has_element?(view, "button[data-call=start][disabled]") render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) @@ -235,7 +234,7 @@ if Code.ensure_loaded?(AudioFlow.Duplex.Moshi) do render_hook(view, "call_audio", %{"generation" => generation, "pcm" => chunk()}) assert_reply(view, %{ok: false, error: "overloaded"}) - assert render(view) =~ "Live: microphone and playback on" + assert render(view) =~ "Live · microphone on" end test "settings and a second conversation are refused while one is active" do diff --git a/examples/chat/test/openai_live_test.exs b/examples/chat/test/openai_live_test.exs new file mode 100644 index 0000000..5d3c86b --- /dev/null +++ b/examples/chat/test/openai_live_test.exs @@ -0,0 +1,235 @@ +defmodule Chat.OpenAILiveTest do + use ExUnit.Case, async: false + import Phoenix.ConnTest + import Phoenix.LiveViewTest + + @endpoint ChatWeb.Endpoint + @chunk 3_840 + + # A local peer with the OpenAI Realtime GA event framing. It reports each + # connection and client event to the test and pushes the events the test + # sends. It never acts on its own. + defmodule Peer do + @behaviour WebSock + + def init(owner) do + send(owner, {:peer, self()}) + {:ok, owner} + end + + def handle_in({data, opcode: :text}, owner) do + send(owner, {:client, JSON.decode!(data)}) + {:ok, owner} + end + + def handle_info({:events, events}, owner), + do: {:push, Enum.map(events, &{:text, JSON.encode!(&1)}), owner} + + def terminate(_reason, owner) do + send(owner, :peer_closed) + :ok + end + end + + defmodule Server do + def init(owner), do: owner + + def call(conn, owner) do + send(owner, {:upgrade, conn.query_string}) + conn |> WebSockAdapter.upgrade(Peer, owner, []) |> Plug.Conn.halt() + end + end + + setup do + names = ["CHAT_MODE", "OPENAI_API_KEY", "OPENAI_REALTIME_MODEL", "OPENAI_REALTIME_ENDPOINT"] + original = Map.new(names, &{&1, System.get_env(&1)}) + + on_exit(fn -> + for {name, value} <- original, + do: if(value, do: System.put_env(name, value), else: System.delete_env(name)) + end) + + System.put_env(%{ + "CHAT_MODE" => "openai", + "OPENAI_API_KEY" => "fixture-key", + "OPENAI_REALTIME_MODEL" => "fixture-model" + }) + + :ok + end + + # The server reads the provider endpoint only from its environment. + defp openai_peer do + server = + start_supervised!( + {Bandit, plug: {Server, self()}, port: 0, ip: {127, 0, 0, 1}, startup_log: false} + ) + + {:ok, {_, port}} = ThousandIsland.listener_info(server) + System.put_env("OPENAI_REALTIME_ENDPOINT", "ws://127.0.0.1:#{port}/v1/realtime") + end + + defp connect(view) do + render_hook(view, "call_start", %{"endpoint" => "ws://127.0.0.1:1/ignored"}) + assert_reply(view, %{ok: true, generation: generation}) + assert_receive {:upgrade, "model=fixture-model"}, 2_000 + assert_receive {:peer, peer} + send(peer, {:events, [%{type: "session.created", session: %{}}]}) + assert_receive {:client, %{"type" => "session.update", "session" => session}}, 2_000 + assert render(view) =~ "Connecting…" + send(peer, {:events, [%{type: "session.updated", session: session}]}) + assert_push_event(view, "call_ready", %{generation: ^generation}, 2_000) + {generation, peer, session} + end + + defp audio(view, generation) do + pcm = Base.encode64(:binary.copy(<<0>>, @chunk)) + render_hook(view, "call_audio", %{"generation" => generation, "pcm" => pcm}) + end + + defp utterance(peer, user, transcript, response, item, text) do + send( + peer, + {:events, + [ + %{type: "input_audio_buffer.speech_started", item_id: user, audio_start_ms: 0}, + %{type: "input_audio_buffer.speech_stopped", item_id: user, audio_end_ms: 800}, + %{type: "response.created", response: %{id: response}}, + %{ + type: "response.output_audio.delta", + response_id: response, + item_id: item, + content_index: 0, + delta: Base.encode64(:binary.copy(<<0>>, 4_800)) + }, + %{type: "response.output_audio_transcript.delta", response_id: response, delta: text}, + %{ + type: "conversation.item.input_audio_transcription.completed", + item_id: user, + transcript: transcript + } + ]} + ) + end + + defp messages(view) do + for %{role: role, text: text} <- :sys.get_state(view.pid).socket.assigns.messages, + do: {role, text} + end + + test "OpenAI mode opens the always-on controls with the voice choice" do + {:ok, view, html} = live(build_conn(), "/") + assert html =~ "OpenAI live conversation" + assert html =~ "Start conversation" + assert has_element?(view, "select[name=voice]") + assert has_element?(view, "button[data-call=stop][disabled]") + refute has_element?(view, "#prompt") + refute has_element?(view, "#recorder") + refute view |> element("#duplex") |> render() =~ "Moshi" + assert :sys.get_state(view.pid).socket.assigns.session == nil + end + + test "one connection hears several utterances while the microphone streams" do + openai_peer() + {:ok, view, _} = live(build_conn(), "/") + view |> element("#configuration") |> render_submit(%{"mode" => "openai", "voice" => "cedar"}) + {generation, peer, session} = connect(view) + assert session["audio"]["output"]["voice"] == "cedar" + assert render(view) =~ "Live · microphone on" + + for _ <- 1..10 do + audio(view, generation) + assert_reply(view, %{ok: true}) + assert_receive {:client, %{"type" => "input_audio_buffer.append"}} + end + + utterance(peer, "user_1", "Hello there", "resp_1", "item_1", "Hi! How can I help?") + assert_push_event(view, "call_flush", %{generation: ^generation}, 2_000) + + assert_push_event(view, "call_play", %{generation: ^generation, output: "item_1", pcm: pcm}) + assert byte_size(Base.decode64!(pcm)) == 4_800 + + # The microphone keeps streaming while reply audio plays. + audio(view, generation) + assert_reply(view, %{ok: true}) + + send( + peer, + {:events, + [%{type: "response.done", response: %{id: "resp_1", status: "completed", output: []}}]} + ) + + assert eventually(fn -> + messages(view) == [{"user", "Hello there"}, {"assistant", "Hi! How can I help?"}] + end) + + # The second utterance interrupts the reply; the browser reports what played. + utterance(peer, "user_2", "Stop, another question", "resp_2", "item_2", "Sure.") + assert_push_event(view, "call_flush", %{generation: ^generation}, 2_000) + + render_hook(view, "call_played", %{ + "generation" => generation, + "output" => "item_1", + "ms" => 40 + }) + + assert_receive {:client, + %{ + "type" => "conversation.item.truncate", + "item_id" => "item_1", + "audio_end_ms" => 40 + }}, + 2_000 + + assert eventually(fn -> + messages(view) == [ + {"user", "Hello there"}, + {"assistant", "Hi! How can I help?"}, + {"user", "Stop, another question"}, + {"assistant", "Sure."} + ] + end) + + # Both utterances used the same provider connection; none was committed by the client. + refute_received {:peer, _} + refute_received {:client, %{"type" => "input_audio_buffer.commit"}} + refute_received {:client, %{"type" => "response.create"}} + + render_hook(view, "call_stop", %{"generation" => generation}) + assert_push_event(view, "call_stopped", %{generation: ^generation}) + assert_receive :peer_closed, 2_000 + assert render(view) =~ "Not connected" + end + + test "a provider error stops the call with its code and a new call starts fresh" do + openai_peer() + {:ok, view, _} = live(build_conn(), "/") + {generation, peer, _} = connect(view) + + send( + peer, + {:events, + [%{type: "error", error: %{type: "server_error", code: "boom", message: "provider-message-text"}}]} + ) + + assert_push_event(view, "call_stopped", %{generation: ^generation}, 2_000) + assert has_element?(view, "[role=alert]", "Conversation error: provider error boom") + refute render(view) =~ "provider-message-text" + assert_receive :peer_closed, 2_000 + + {next, _peer, _} = connect(view) + assert next == generation + 1 + end + + defp eventually(fun, tries \\ 100) + defp eventually(_, 0), do: false + + defp eventually(fun, tries) do + if fun.() do + true + else + Process.sleep(20) + eventually(fun, tries - 1) + end + end +end From 4cf928fe447ef73595fe03973caa80de851e8355 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 23:22:17 +0200 Subject: [PATCH 12/12] fix(chat): preserve completed reply history and response state --- docs/providers.md | 2 + examples/chat/assets/js/duplex.js | 22 +++--- examples/chat/assets/test/duplex.test.js | 13 ++++ examples/chat/lib/chat_web/live/chat_live.ex | 35 +++++---- examples/chat/test/openai_live_test.exs | 75 +++++++++++++++++++- 5 files changed, 125 insertions(+), 22 deletions(-) diff --git a/docs/providers.md b/docs/providers.md index bf497e8..f3aed1f 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -317,6 +317,8 @@ the code or type, never the message). Tool calls fail it with `:unsupported_tool_call`, because no tools are configured. All `AudioFlow.Duplex` bounds apply; `:max_response_bytes` (64 MiB) is about 17 minutes of base64 reply audio per session. +The chat example sets this bound to 256 MiB for OpenAI calls, to allow the +30-minute call limit to apply before the response byte limit in ordinary use. `mix test test/duplex_openai_test.exs` checks the handshake order, server VAD configuration, several utterances on one socket, continuous silence, diff --git a/examples/chat/assets/js/duplex.js b/examples/chat/assets/js/duplex.js index 7a13ead..3e10540 100644 --- a/examples/chat/assets/js/duplex.js +++ b/examples/chat/assets/js/duplex.js @@ -255,7 +255,7 @@ export const Duplex = { if (samples.length === 0) return; if (output !== null && call.output?.id !== output) { - call.output = { id: output, spans: [], rendered: 0, dropping: false }; + call.output = { id: output, spans: [], rendered: 0, rate, dropping: false }; } const reply = output === null ? null : call.output; const context = call.context; @@ -280,7 +280,7 @@ export const Duplex = { call.next = start + buffer.duration; if (reply) { this.fold(call, reply); - reply.spans.push([start, call.next]); + reply.spans.push([start, call.next, samples.length]); } }, @@ -294,25 +294,29 @@ export const Duplex = { // Moves fully heard spans into a sum, so the span list stays short. fold(call, reply) { const heard = this.heard(call); - reply.spans = reply.spans.filter(([start, end]) => { + reply.spans = reply.spans.filter(([_start, end, samples]) => { if (end > heard) return true; - reply.rendered += end - start; + reply.rendered += samples; return false; }); }, - // Seconds of this reply that were heard. - rendered(call, reply) { + // Count exact scheduled samples and round only the partially rendered span. + renderedSamples(call, reply) { const heard = this.heard(call); let sum = reply.rendered; - for (const [start, end] of reply.spans) sum += Math.max(0, Math.min(heard, end) - start); + for (const [start, end, samples] of reply.spans) { + sum += Math.min(samples, Math.max(0, Math.round((Math.min(heard, end) - start) * reply.rate))); + } return sum; }, // User speech: stop queued model audio, keep the microphone, report progress. flush(call) { const reply = call.output; - const ms = reply ? Math.max(0, Math.floor(this.rendered(call, reply) * 1000)) : 0; + if (reply) this.fold(call, reply); + const ms = reply ? Math.floor(this.renderedSamples(call, reply) * 1000 / reply.rate) : 0; + const complete = reply && reply.spans.length === 0 && !reply.dropping; for (const source of call.sources) { source.onended = null; source.stop(); @@ -323,7 +327,7 @@ export const Duplex = { if (!reply) return; call.cut = reply.id; call.output = null; - this.pushEvent("call_played", { generation: call.generation, output: reply.id, ms }); + if (!complete) this.pushEvent("call_played", { generation: call.generation, output: reply.id, ms }); }, release(call) { diff --git a/examples/chat/assets/test/duplex.test.js b/examples/chat/assets/test/duplex.test.js index 6301dec..2436d01 100644 --- a/examples/chat/assets/test/duplex.test.js +++ b/examples/chat/assets/test/duplex.test.js @@ -346,3 +346,16 @@ test("reply audio past the playback limit drops the rest of that reply", async ( view.handlers.call_play({ generation: 6, output: "item_2", pcm: pcm(1_920), rate: 24_000 }); assert.equal(context.sources.length, 4); }); + +test("a fully played reply at a large clock time keeps its provider history", async () => { + const view = await connect(7, { playbackAhead: "60" }); + const context = contexts.at(-1); + context.currentTime = 123.46; + for (let i = 0; i < 50; i++) { + view.handlers.call_play({ generation: 7, output: "complete", pcm: pcm(2_400), rate: 24_000 }); + } + context.currentTime = 130; + view.handlers.call_flush({ generation: 7 }); + assert.equal(view.sent("call_played").length, 0); + assert.equal(microphone.track.stopped, undefined); +}); diff --git a/examples/chat/lib/chat_web/live/chat_live.ex b/examples/chat/lib/chat_web/live/chat_live.ex index 964e4fe..99ea642 100644 --- a/examples/chat/lib/chat_web/live/chat_live.ex +++ b/examples/chat/lib/chat_web/live/chat_live.ex @@ -394,6 +394,7 @@ defmodule ChatWeb.ChatLive do ready: false, turns: turns, reply_id: nil, + reply_response: nil, text_at: nil, output: nil, users: [] @@ -410,7 +411,12 @@ defmodule ChatWeb.ChatLive do # A model failure must not stop the LiveView. Duplex monitors this owner. defp start_duplex(adapter) do - Duplex.start(owner: self(), adapter: adapter) + limits = + if elem(adapter, 0) == Duplex.OpenAIRealtime, + do: [max_response_bytes: 256 * 1024 * 1024], + else: [] + + Duplex.start([owner: self(), adapter: adapter] ++ limits) rescue error in ArgumentError -> {:error, Exception.message(error)} end @@ -452,8 +458,9 @@ defmodule ChatWeb.ChatLive do %{call: call} = socket.assigns socket = add_message(socket, "user", "", pending: true, live: true) - users = - Enum.take(call.users ++ [{item, List.last(socket.assigns.messages).id}], -@call_max_pending) + pending = call.users ++ [{item, List.last(socket.assigns.messages).id}] + {removed, users} = Enum.split(pending, max(length(pending) - @call_max_pending, 0)) + socket = Enum.reduce(removed, socket, fn {_, id}, socket -> settle(socket, id) end) socket |> assign(call: %{call | output: nil, users: users}) @@ -470,27 +477,29 @@ defmodule ChatWeb.ChatLive do end end - defp call_event(socket, {:response, _id, :created}) do + defp call_event(socket, {:response, id, :created}) do %{call: call} = socket.assigns socket = if call.reply_id, do: settle(socket, call.reply_id), else: socket socket = add_message(socket, "assistant", "", pending: true) - assign(socket, call: %{call | reply_id: List.last(socket.assigns.messages).id}) + assign(socket, + call: %{call | reply_id: List.last(socket.assigns.messages).id, reply_response: id} + ) |> trim_messages() end - defp call_event(%{assigns: %{call: %{reply_id: nil}}} = socket, {:response, _id, _status}), - do: socket - - defp call_event(socket, {:response, _id, status}) do - %{call: call} = socket.assigns - + defp call_event( + %{assigns: %{call: %{reply_response: id} = call}} = socket, + {:response, id, status} + ) do socket |> update_message(call.reply_id, &%{&1 | note: reply_note(status, &1.text)}) |> settle(call.reply_id) - |> assign(call: %{call | reply_id: nil}) + |> assign(call: %{call | reply_id: nil, reply_response: nil}) end + defp call_event(socket, {:response, _id, _status}), do: socket + defp call_event(socket, {:output, item}), do: assign(socket, call: %{socket.assigns.call | output: item}) @@ -521,6 +530,8 @@ defmodule ChatWeb.ChatLive do when id != nil, do: update_message(socket, id, &%{&1 | text: &1.text <> text, pending: false}) + defp call_text(%{assigns: %{call: %{turns: true}}} = socket, _text), do: socket + # Moshi does not mark turns. A pause in the model text starts a new message, # and the conversation keeps only the latest messages. defp call_text(socket, text) do diff --git a/examples/chat/test/openai_live_test.exs b/examples/chat/test/openai_live_test.exs index 5d3c86b..259c326 100644 --- a/examples/chat/test/openai_live_test.exs +++ b/examples/chat/test/openai_live_test.exs @@ -209,7 +209,12 @@ defmodule Chat.OpenAILiveTest do send( peer, {:events, - [%{type: "error", error: %{type: "server_error", code: "boom", message: "provider-message-text"}}]} + [ + %{ + type: "error", + error: %{type: "server_error", code: "boom", message: "provider-message-text"} + } + ]} ) assert_push_event(view, "call_stopped", %{generation: ^generation}, 2_000) @@ -221,6 +226,74 @@ defmodule Chat.OpenAILiveTest do assert next == generation + 1 end + test "old response completion cannot close the current reply and clearing text stays clear" do + openai_peer() + {:ok, view, _} = live(build_conn(), "/") + {_generation, peer, _} = connect(view) + + send( + peer, + {:events, + [ + %{type: "response.created", response: %{id: "old"}}, + %{ + type: "response.output_audio_transcript.delta", + response_id: "old", + delta: "Old reply" + }, + %{type: "response.created", response: %{id: "new"}}, + %{type: "response.output_audio_transcript.delta", response_id: "new", delta: "New"}, + %{type: "response.done", response: %{id: "old", status: "cancelled", output: []}}, + %{type: "response.output_audio_transcript.delta", response_id: "new", delta: " reply"} + ]} + ) + + assert eventually(fn -> + messages(view) == [{"assistant", "Old reply"}, {"assistant", "New reply"}] + end) + + render_hook(view, "new_chat", %{}) + + send( + peer, + {:events, + [ + %{ + type: "response.output_audio_transcript.delta", + response_id: "new", + delta: " after clearing" + }, + %{type: "response.done", response: %{id: "new", status: "completed", output: []}} + ]} + ) + + assert eventually(fn -> + :sys.get_state(view.pid).socket.assigns.call.reply_response == nil + end) + + assert messages(view) == [] + end + + test "pending transcript eviction removes waiting messages" do + openai_peer() + {:ok, view, _} = live(build_conn(), "/") + {_generation, peer, _} = connect(view) + + for n <- 1..20 do + send( + peer, + {:events, + [%{type: "input_audio_buffer.speech_started", item_id: "u#{n}", audio_start_ms: n * 100}]} + ) + end + + assert eventually(fn -> + state = :sys.get_state(view.pid).socket.assigns + Enum.count_until(state.call.users, 17) == 16 and + Enum.count_until(state.messages, 17) == 16 + end) + end + defp eventually(fun, tries \\ 100) defp eventually(_, 0), do: false