@firstpick/pi-package-webui 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (310) hide show
  1. package/DEVELOPMENT.md +151 -12
  2. package/README.md +34 -6
  3. package/TECHNICAL.md +75 -8
  4. package/bin/pi-webui.mjs +5390 -11423
  5. package/index.ts +10 -3
  6. package/lib/component-update-state.mjs +2 -2
  7. package/lib/git-workflow-preference-values.mjs +122 -0
  8. package/lib/git-workflow-preferences.mjs +35 -563
  9. package/lib/package-updates.mjs +260 -0
  10. package/lib/rpc-supervisor-client.mjs +8 -4
  11. package/lib/server/app-runners.mjs +1667 -0
  12. package/lib/server/codex-fast-mode.mjs +161 -0
  13. package/lib/server/conversation-mode.mjs +218 -0
  14. package/lib/server/conversation-voice.mjs +318 -0
  15. package/lib/server/extension-ui-requests.mjs +114 -0
  16. package/lib/server/git-generation.mjs +459 -0
  17. package/lib/server/git-mutations.mjs +1827 -0
  18. package/lib/server/git-reads.mjs +608 -0
  19. package/lib/server/git-worktree-sessions.mjs +408 -0
  20. package/lib/server/helper-requests.mjs +82 -0
  21. package/lib/server/no-project-workspaces.mjs +103 -0
  22. package/lib/server/rpc-transports.mjs +394 -0
  23. package/lib/server/settings-store.mjs +544 -0
  24. package/lib/server/sse-delivery.mjs +138 -0
  25. package/lib/server/workspace-files.mjs +563 -0
  26. package/lib/update/supervisor.mjs +4 -0
  27. package/lib/webui-workspaces.mjs +2 -0
  28. package/package.json +4 -4
  29. package/public/activity-agents-controller.mjs +269 -0
  30. package/public/activity-events-controller.mjs +236 -0
  31. package/public/activity-intercom-controller.mjs +627 -0
  32. package/public/activity-queue-controller.mjs +534 -0
  33. package/public/activity-todo-view.mjs +89 -0
  34. package/public/activity-usage-controller.mjs +589 -0
  35. package/public/app.js +3761 -3886
  36. package/public/conversation-overview.css +84 -0
  37. package/public/conversation-overview.mjs +193 -0
  38. package/public/draft-conversations.mjs +135 -0
  39. package/public/focused-composer-controls.css +111 -0
  40. package/public/focused-composer-controls.mjs +143 -0
  41. package/public/focused-composer-disclosure.mjs +223 -0
  42. package/public/focused-shell-adapter.css +264 -0
  43. package/public/focused-shell-adapter.mjs +257 -0
  44. package/public/index.html +137 -80
  45. package/public/model-catalog-order.mjs +63 -0
  46. package/public/platform-event-stream.mjs +64 -0
  47. package/public/project-artifact-controller.mjs +218 -0
  48. package/public/project-file-viewer-controller.mjs +383 -0
  49. package/public/project-git-tools-controller.mjs +181 -0
  50. package/public/project-runners-controller.mjs +220 -0
  51. package/public/service-worker.js +52 -1
  52. package/public/session-attention-scheduler.mjs +182 -0
  53. package/public/session-composer-store.mjs +56 -0
  54. package/public/session-context.mjs +51 -0
  55. package/public/session-extension-requests.mjs +63 -0
  56. package/public/session-shelf-state.mjs +151 -0
  57. package/public/session-shelves.css +171 -0
  58. package/public/session-shelves.mjs +95 -0
  59. package/public/settings-navigation-controller.mjs +249 -0
  60. package/public/settings-navigation.css +61 -0
  61. package/public/settings-resource-controller.mjs +232 -0
  62. package/public/settings-workspace.css +19 -0
  63. package/public/settings-workspace.mjs +175 -0
  64. package/public/shell-actions.mjs +87 -0
  65. package/public/shell-attention-inbox.css +72 -0
  66. package/public/shell-attention-inbox.mjs +198 -0
  67. package/public/shell-context-actions.css +61 -0
  68. package/public/shell-context-actions.mjs +168 -0
  69. package/public/shell-inspector-resize.mjs +124 -0
  70. package/public/shell-navigation-resize.mjs +107 -0
  71. package/public/shell-navigation.mjs +127 -0
  72. package/public/shell-preferences.mjs +108 -0
  73. package/public/shell-surfaces.mjs +99 -0
  74. package/public/shell-tools-launcher.css +97 -0
  75. package/public/shell-tools-launcher.mjs +222 -0
  76. package/public/shell-view-host.mjs +115 -0
  77. package/public/shell-workspace.css +266 -0
  78. package/public/shell-workspace.mjs +402 -0
  79. package/public/sidebar-update-menu.css +190 -0
  80. package/public/sidebar-update-menu.mjs +512 -0
  81. package/public/styles.css +322 -169
  82. package/public/subagent-launch-slot-state.mjs +2 -2
  83. package/public/themed-selects.css +156 -0
  84. package/public/workspace-choices.mjs +104 -0
  85. package/tests/activity-agents-controller.test.mjs +652 -0
  86. package/tests/activity-events-controller.test.mjs +511 -0
  87. package/tests/app-runner-terminal-static.test.mjs +3 -3
  88. package/tests/append-system-http.test.mjs +7 -6
  89. package/tests/append-system-selector-static.test.mjs +6 -6
  90. package/tests/aur-review-widget-static.test.mjs +11 -3
  91. package/tests/boot-failure-diagnostics.test.mjs +8 -3
  92. package/tests/browser/action-feedback-gutter.spec.mjs +251 -0
  93. package/tests/browser/activity-intercom-controller.spec.mjs +457 -0
  94. package/tests/browser/activity-navigation-integration.spec.mjs +45 -0
  95. package/tests/browser/activity-owner-integration.spec.mjs +201 -0
  96. package/tests/browser/activity-queue-controller.spec.mjs +405 -0
  97. package/tests/browser/activity-section-picker.spec.mjs +294 -0
  98. package/tests/browser/activity-todo-view.spec.mjs +60 -0
  99. package/tests/browser/activity-usage-controller.spec.mjs +416 -0
  100. package/tests/browser/compact-layout-integration.spec.mjs +58 -0
  101. package/tests/browser/composer-action-grid-reorder.spec.mjs +16 -0
  102. package/tests/browser/composer-disclosure.spec.mjs +389 -0
  103. package/tests/browser/composer-toolbar-polish.spec.mjs +343 -0
  104. package/tests/browser/control-deck-component-updates.spec.mjs +5 -14
  105. package/tests/browser/control-deck-side-panels.spec.mjs +27 -12
  106. package/tests/browser/control-visibility.spec.mjs +5 -0
  107. package/tests/browser/controls-layout.spec.mjs +21 -2
  108. package/tests/browser/conversation-overview.spec.mjs +251 -0
  109. package/tests/browser/draft-conversations.spec.mjs +276 -0
  110. package/tests/browser/empty-startup-fixture.mjs +135 -0
  111. package/tests/browser/empty-startup.spec.mjs +282 -0
  112. package/tests/browser/events-tree-context-menu.spec.mjs +1 -0
  113. package/tests/browser/focused-composer-more.spec.mjs +127 -0
  114. package/tests/browser/focused-model-shortcuts.spec.mjs +120 -0
  115. package/tests/browser/focused-navigation-fixture.mjs +32 -0
  116. package/tests/browser/focused-project-activity.spec.mjs +111 -0
  117. package/tests/browser/focused-shell-integration.spec.mjs +208 -0
  118. package/tests/browser/folder-picker-layout-fixture.mjs +13 -0
  119. package/tests/browser/folder-picker-layout.spec.mjs +302 -0
  120. package/tests/browser/footer-model-advanced-layout.spec.mjs +27 -14
  121. package/tests/browser/git-setup-cancel.spec.mjs +251 -0
  122. package/tests/browser/guided-git-fallback.spec.mjs +40 -21
  123. package/tests/browser/inspector-header.spec.mjs +221 -0
  124. package/tests/browser/inspector-overview-integration.spec.mjs +104 -0
  125. package/tests/browser/inspector-resize.spec.mjs +227 -0
  126. package/tests/browser/inspector-topic-overflow.spec.mjs +56 -0
  127. package/tests/browser/interaction-action-discovery.spec.mjs +332 -0
  128. package/tests/browser/interaction-attention-inbox.spec.mjs +364 -0
  129. package/tests/browser/interaction-attention-integration.spec.mjs +53 -0
  130. package/tests/browser/interaction-composer-controls.spec.mjs +267 -0
  131. package/tests/browser/interaction-composer-integration.spec.mjs +175 -0
  132. package/tests/browser/interaction-continuity.spec.mjs +50 -26
  133. package/tests/browser/interaction-model-picker.spec.mjs +86 -0
  134. package/tests/browser/last-terminal-close.spec.mjs +280 -0
  135. package/tests/browser/mobile-foundation.spec.mjs +172 -20
  136. package/tests/browser/model-catalog-groups.spec.mjs +104 -0
  137. package/tests/browser/more-row-menus.spec.mjs +258 -0
  138. package/tests/browser/new-tab-hit-target.spec.mjs +228 -0
  139. package/tests/browser/no-project-conversation.spec.mjs +113 -0
  140. package/tests/browser/optimistic-prompt.spec.mjs +3 -0
  141. package/tests/browser/overhaul-w7-accessibility.spec.mjs +227 -0
  142. package/tests/browser/overhaul-w7-capabilities.spec.mjs +298 -0
  143. package/tests/browser/overhaul-w7-companions.spec.mjs +290 -0
  144. package/tests/browser/overhaul-w7-focus-repairs.spec.mjs +210 -0
  145. package/tests/browser/overhaul-w7-layout-repairs.spec.mjs +183 -0
  146. package/tests/browser/overhaul-w7-parent-repairs.spec.mjs +97 -0
  147. package/tests/browser/overhaul-w7-pwa.spec.mjs +247 -0
  148. package/tests/browser/overhaul-w7-responsive.spec.mjs +450 -0
  149. package/tests/browser/overhaul-w7-update.spec.mjs +215 -0
  150. package/tests/browser/overhaul-w7-zoom.spec.mjs +243 -0
  151. package/tests/browser/overview-agent-ownership.spec.mjs +45 -0
  152. package/tests/browser/persistent-ui-layout.spec.mjs +3 -0
  153. package/tests/browser/project-artifact-controller.spec.mjs +324 -0
  154. package/tests/browser/project-artifact-integration.spec.mjs +103 -0
  155. package/tests/browser/project-file-buffer-integration.spec.mjs +230 -0
  156. package/tests/browser/project-git-tools-integration.spec.mjs +369 -0
  157. package/tests/browser/session-fixture.mjs +118 -0
  158. package/tests/browser/session-ownership.spec.mjs +175 -0
  159. package/tests/browser/session-shelves-integration.spec.mjs +219 -0
  160. package/tests/browser/session-shelves.spec.mjs +340 -0
  161. package/tests/browser/session-sidebar-resize.spec.mjs +138 -0
  162. package/tests/browser/session-summary.spec.mjs +17 -12
  163. package/tests/browser/settings-complete-home.spec.mjs +463 -0
  164. package/tests/browser/settings-entrypoint.spec.mjs +104 -0
  165. package/tests/browser/settings-navigation-controller.spec.mjs +383 -0
  166. package/tests/browser/settings-navigation-integration.spec.mjs +348 -0
  167. package/tests/browser/settings-resource-lifetime.spec.mjs +349 -0
  168. package/tests/browser/settings-workspace-integration.spec.mjs +132 -0
  169. package/tests/browser/shell-ownership.spec.mjs +398 -0
  170. package/tests/browser/shell-rollout-fixture.mjs +259 -0
  171. package/tests/browser/shell-rollout.spec.mjs +357 -0
  172. package/tests/browser/shell-tools-launcher.spec.mjs +260 -0
  173. package/tests/browser/shell-workspace.spec.mjs +433 -0
  174. package/tests/browser/side-panel-section-reorder.spec.mjs +3 -1
  175. package/tests/browser/sidebar-floating-tooltips.spec.mjs +37 -0
  176. package/tests/browser/sidebar-update-integration.spec.mjs +277 -0
  177. package/tests/browser/sidebar-update-menu.spec.mjs +402 -0
  178. package/tests/browser/sidebar-update-progress.spec.mjs +472 -0
  179. package/tests/browser/stream-output-isolation.spec.mjs +6 -3
  180. package/tests/browser/themed-selects.spec.mjs +297 -0
  181. package/tests/browser/thread-start-flow.spec.mjs +481 -0
  182. package/tests/browser/ui-polish-activity-controls.spec.mjs +177 -0
  183. package/tests/browser/ui-polish-features.spec.mjs +85 -0
  184. package/tests/browser/ui-polish-file-header.spec.mjs +43 -0
  185. package/tests/browser/ui-polish-local-git.spec.mjs +183 -0
  186. package/tests/browser/ui-polish-mobile-recovery.spec.mjs +36 -0
  187. package/tests/browser/ui-polish-navigation.spec.mjs +127 -0
  188. package/tests/browser/ui-polish-session-actions.spec.mjs +282 -0
  189. package/tests/browser/user-noticeable-fixes.spec.mjs +10 -3
  190. package/tests/browser/windows-drive-parent.spec.mjs +4 -2
  191. package/tests/browser/workspace-draft-selection.spec.mjs +266 -0
  192. package/tests/codex-fast-mode-static.test.mjs +16 -11
  193. package/tests/codex-speed-mode-browser-state.test.mjs +6 -3
  194. package/tests/codex-usage-source.test.mjs +4 -3
  195. package/tests/component-update-api-static.test.mjs +2 -2
  196. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  197. package/tests/control-deck-component-updates-static.test.mjs +9 -4
  198. package/tests/control-visibility-static.test.mjs +3 -3
  199. package/tests/controls-layout-static.test.mjs +5 -5
  200. package/tests/conversation-overview-adapter.test.mjs +100 -0
  201. package/tests/document-artifact-static.test.mjs +2 -1
  202. package/tests/draft-conversations.test.mjs +205 -0
  203. package/tests/empty-startup-launcher.test.mjs +197 -0
  204. package/tests/events-tree-context-menu-static.test.mjs +22 -18
  205. package/tests/fake-pi-session-ownership.test.mjs +302 -0
  206. package/tests/fast-mode-client-static.test.mjs +1 -1
  207. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  208. package/tests/feature-system-prompt-optional-feature-static.test.mjs +1 -1
  209. package/tests/file-viewer-image-static.test.mjs +15 -11
  210. package/tests/file-viewer-search-static.test.mjs +5 -5
  211. package/tests/fixtures/fake-pi.mjs +41 -9
  212. package/tests/footer-provider-usage-visual-static.test.mjs +7 -6
  213. package/tests/foreground-transcript-catch-up-static.test.mjs +7 -4
  214. package/tests/git-footer-context-menu-static.test.mjs +1 -1
  215. package/tests/git-panel-file-preview-static.test.mjs +41 -48
  216. package/tests/git-panel-live-updates-static.test.mjs +2 -1
  217. package/tests/git-workflow-dispatch.test.mjs +66 -0
  218. package/tests/git-workflow-preferences.test.mjs +9 -1
  219. package/tests/guided-git-activation-static.test.mjs +14 -11
  220. package/tests/guided-git-fallback-ui-static.test.mjs +8 -5
  221. package/tests/guided-git-message-reliability-static.test.mjs +10 -6
  222. package/tests/guided-git-publication-backend-static.test.mjs +16 -11
  223. package/tests/http-endpoints-harness.test.mjs +21 -9
  224. package/tests/interaction-state-stability-static.test.mjs +4 -3
  225. package/tests/intercom-conversation-viewer-static.test.mjs +29 -17
  226. package/tests/intercom-tag-layout-static.test.mjs +13 -12
  227. package/tests/intercom-tag-overflow-layout.test.mjs +11 -10
  228. package/tests/main-output-loading-static.test.mjs +4 -4
  229. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  230. package/tests/mobile-compact-layout.test.mjs +2 -2
  231. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  232. package/tests/mobile-foundation-static.test.mjs +10 -7
  233. package/tests/mobile-phone-experience-static.test.mjs +3 -2
  234. package/tests/mobile-static.test.mjs +173 -135
  235. package/tests/model-catalog-order.test.mjs +103 -0
  236. package/tests/native-parity.test.mjs +6 -4
  237. package/tests/native-session-choice-owner.test.mjs +102 -0
  238. package/tests/native-update-lifecycle.test.mjs +10 -5
  239. package/tests/no-project-http-harness.test.mjs +328 -0
  240. package/tests/no-project-navigation.test.mjs +54 -0
  241. package/tests/no-project-workspaces.test.mjs +77 -0
  242. package/tests/open-issue-wizard-static.test.mjs +1 -1
  243. package/tests/optional-feature-migration-frontend.test.mjs +4 -4
  244. package/tests/optional-feature-prompt-impact-static.test.mjs +3 -3
  245. package/tests/package-updates.test.mjs +630 -0
  246. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  247. package/tests/platform-event-stream.test.mjs +253 -0
  248. package/tests/project-file-viewer-controller.test.mjs +652 -0
  249. package/tests/project-git-tools-adapter.test.mjs +103 -0
  250. package/tests/project-git-tools-controller.test.mjs +577 -0
  251. package/tests/project-runners-controller.test.mjs +453 -0
  252. package/tests/prompt-input-vertical-scroll-static.test.mjs +3 -3
  253. package/tests/prompt-routing-input-clear-static.test.mjs +2 -2
  254. package/tests/questionnaire-dialog.test.mjs +6 -6
  255. package/tests/queue-edit-reorder-static.test.mjs +48 -51
  256. package/tests/rpc-supervisor-host.test.mjs +4 -1
  257. package/tests/safety-guard-auto-review-static.test.mjs +1 -1
  258. package/tests/sampling-native-controls-user-flow.test.mjs +7 -1
  259. package/tests/server-app-runners.test.mjs +536 -0
  260. package/tests/server-codex-fast-mode.test.mjs +346 -0
  261. package/tests/server-conversation-mode.test.mjs +386 -0
  262. package/tests/server-conversation-voice.test.mjs +426 -0
  263. package/tests/server-extension-ui-requests.test.mjs +357 -0
  264. package/tests/server-git-generation.test.mjs +558 -0
  265. package/tests/server-git-mutations.test.mjs +729 -0
  266. package/tests/server-git-reads.test.mjs +381 -0
  267. package/tests/server-git-worktree-sessions.test.mjs +502 -0
  268. package/tests/server-helper-requests.test.mjs +364 -0
  269. package/tests/server-rpc-transports.test.mjs +553 -0
  270. package/tests/server-settings-store.test.mjs +132 -0
  271. package/tests/server-shell-rollout.test.mjs +478 -0
  272. package/tests/server-sse-delivery.test.mjs +410 -0
  273. package/tests/server-workspace-files.test.mjs +546 -0
  274. package/tests/session-attention-scheduler.test.mjs +514 -0
  275. package/tests/session-composer-store.test.mjs +153 -0
  276. package/tests/session-context.test.mjs +134 -0
  277. package/tests/session-extension-requests.test.mjs +193 -0
  278. package/tests/session-ownership-adapter.test.mjs +130 -0
  279. package/tests/session-sampling-ui-static.test.mjs +10 -4
  280. package/tests/session-send-lifetime.test.mjs +140 -0
  281. package/tests/session-shelf-state.test.mjs +348 -0
  282. package/tests/session-shelves-adapter.test.mjs +79 -0
  283. package/tests/session-summary-lifetime.test.mjs +54 -0
  284. package/tests/settings-resource-controller.test.mjs +548 -0
  285. package/tests/shell-action-adapter.test.mjs +169 -0
  286. package/tests/shell-actions.test.mjs +182 -0
  287. package/tests/shell-navigation.test.mjs +348 -0
  288. package/tests/shell-preferences.test.mjs +367 -0
  289. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  290. package/tests/stream-output-isolation-static.test.mjs +1 -1
  291. package/tests/subagent-gate-visibility.test.mjs +1 -1
  292. package/tests/subagent-launch-slot-state.test.mjs +2 -2
  293. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  294. package/tests/subagent-observability-static.test.mjs +2 -2
  295. package/tests/subagent-reliability-integration.test.mjs +13 -30
  296. package/tests/syntax-highlighting-static.test.mjs +3 -3
  297. package/tests/tab-close-continuity-static.test.mjs +1 -1
  298. package/tests/tab-metadata-ordering.test.mjs +99 -0
  299. package/tests/terminal-cwd-grouping-static.test.mjs +2 -2
  300. package/tests/terminal-tab-prompt-tooltip-static.test.mjs +2 -0
  301. package/tests/terminal-tab-workspace-static.test.mjs +5 -4
  302. package/tests/terminal-tabs-resize-static.test.mjs +1 -1
  303. package/tests/theme-customizer-static.test.mjs +1 -1
  304. package/tests/thread-display-title.test.mjs +44 -0
  305. package/tests/update-api-harness.test.mjs +15 -14
  306. package/tests/update-tab-restore-harness.test.mjs +3 -0
  307. package/tests/webui-settings-locking.test.mjs +2 -2
  308. package/tests/windows-drive-cwd-picker-static.test.mjs +7 -9
  309. package/tests/workspace-choices.test.mjs +114 -0
  310. package/tests/workspace-save-load-static.test.mjs +7 -4
@@ -0,0 +1,426 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { NATURAL_CONVERSATION_FEATURE_ID } from "../lib/server/conversation-mode.mjs";
7
+
8
+ const serviceNames = [
9
+ "conversationVoicesData", "setConversationVoice", "naturalConversationVoiceProviderStatus",
10
+ "naturalConversationUnavailableResponse", "handleNaturalConversationSttTranscribe", "handleNaturalConversationTtsSpeech",
11
+ ];
12
+ const credentialEnvNames = ["OPENAI_API_KEY", "GROQ_API_KEY", "CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID", "XDG_DATA_HOME"];
13
+ const localRequest = { local: true };
14
+ const remoteRequest = { local: false };
15
+ const audioBase64 = Buffer.from("test audio").toString("base64");
16
+ const audioLimit = 24 * 1024 * 1024;
17
+
18
+ function voiceEnvEntries() {
19
+ return Object.entries(process.env).filter(([key]) => key.startsWith("PI_VOICE_") || credentialEnvNames.includes(key));
20
+ }
21
+
22
+ function replaceVoiceEnv(entries) {
23
+ for (const [key] of voiceEnvEntries()) delete process.env[key];
24
+ for (const [key, value] of entries) process.env[key] = value;
25
+ }
26
+
27
+ function httpError(statusCode, message) {
28
+ return (error) => {
29
+ assert.equal(error.statusCode, statusCode);
30
+ if (typeof message === "string") assert.equal(error.message, message);
31
+ else if (message) assert.match(error.message, message);
32
+ return true;
33
+ };
34
+ }
35
+
36
+ function jsonResponse(value, init = {}) {
37
+ return new Response(JSON.stringify(value), { ...init, headers: { "content-type": "application/json" } });
38
+ }
39
+
40
+ test("C2 conversation voice service", { timeout: 20_000 }, async (t) => {
41
+ const savedEnv = voiceEnvEntries();
42
+ const savedFetch = globalThis.fetch;
43
+ const root = await mkdtemp(path.join(tmpdir(), "webui-conversation-voice-"));
44
+ t.after(async () => {
45
+ globalThis.fetch = savedFetch;
46
+ replaceVoiceEnv(savedEnv);
47
+ await rm(root, { recursive: true, force: true });
48
+ });
49
+ replaceVoiceEnv([["PI_VOICE_PROVIDER_TIMEOUT_MS", "1"]]);
50
+ let importFetchCalls = 0;
51
+ globalThis.fetch = () => { importFetchCalls++; throw new Error("Unexpected import-time fetch"); };
52
+ // A fresh instance captures the clamped timeout independently of other tests.
53
+ const voiceModule = await import("../lib/server/conversation-voice.mjs?c2-contract");
54
+ const { createConversationVoiceService, VOICE_AUDIO_JSON_BODY_LIMIT_BYTES } = voiceModule;
55
+ assert.equal(importFetchCalls, 0);
56
+ let fixtureIndex = 0;
57
+
58
+ async function run(name, fn) {
59
+ await t.test(name, { timeout: 5_000 }, async (subtest) => {
60
+ const directory = path.join(root, String(fixtureIndex++));
61
+ await mkdir(directory);
62
+ const configPath = path.join(directory, "voice.json");
63
+ const dataHome = path.join(directory, "data");
64
+ replaceVoiceEnv([
65
+ ["PI_VOICE_CONFIG_PATH", configPath], ["XDG_DATA_HOME", dataHome],
66
+ ["PI_VOICE_PROVIDER_TIMEOUT_MS", "999999"],
67
+ ]);
68
+ const calls = { fetch: [], feature: [], rpc: [], snapshot: [], format: [], truncate: [] };
69
+ let fetchResponse = () => { throw new Error("Unexpected provider dispatch"); };
70
+ globalThis.fetch = async (...args) => {
71
+ calls.fetch.push(args);
72
+ return fetchResponse(...args);
73
+ };
74
+ const feature = { available: true, commands: ["voice", "talk"], unavailableReason: "Companion unavailable" };
75
+ const response = { success: true, data: { accepted: true } };
76
+ let rpcResponse = async () => response;
77
+ const tab = { id: "requested-tab", rpc: { async send(...args) {
78
+ calls.rpc.push(args);
79
+ return rpcResponse(...args);
80
+ } } };
81
+ const mode = { featureId: NATURAL_CONVERSATION_FEATURE_ID, enabled: true, available: true, uiState: "listening" };
82
+ const service = createConversationVoiceService({
83
+ async naturalConversationFeatureData(target) { calls.feature.push(target); return feature; },
84
+ naturalConversationModeSnapshot(target, patch = {}) { calls.snapshot.push([target, patch]); return { ...mode, ...patch }; },
85
+ isLocalRequest: (request) => request.local === true,
86
+ makeHttpError: (statusCode, message) => Object.assign(new Error(message), { statusCode }),
87
+ formatBytes(bytes) { calls.format.push(bytes); return `${bytes} bytes`; },
88
+ truncateStatusText(value, limit) { calls.truncate.push([value, limit]); return String(value).slice(0, limit); },
89
+ });
90
+ await fn({
91
+ service, calls, feature, response, tab, mode, directory, configPath, dataHome, subtest,
92
+ setFetch: (fn) => { fetchResponse = fn; },
93
+ setRpc: (fn) => { rpcResponse = fn; },
94
+ });
95
+ });
96
+ }
97
+
98
+ await run("exports the exact contract and construction calls no dependencies", async ({ calls }) => {
99
+ assert.deepEqual(Object.keys(voiceModule).sort(), ["VOICE_AUDIO_JSON_BODY_LIMIT_BYTES", "createConversationVoiceService"]);
100
+ assert.equal(VOICE_AUDIO_JSON_BODY_LIMIT_BYTES, Math.ceil(audioLimit * 1.4) + 1024 * 1024);
101
+ const fail = () => { throw new Error("Unexpected factory dependency call"); };
102
+ const service = createConversationVoiceService({
103
+ naturalConversationFeatureData: fail, naturalConversationModeSnapshot: fail,
104
+ isLocalRequest: fail, makeHttpError: fail, formatBytes: fail, truncateStatusText: fail,
105
+ });
106
+ assert.deepEqual(Object.keys(service).sort(), [...serviceNames].sort());
107
+ assert.ok(Object.values(calls).every((entries) => entries.length === 0));
108
+ });
109
+
110
+ await run("catalog survives absent or malformed config and keeps its built-in order", async ({ service, configPath }) => {
111
+ const initial = await service.conversationVoicesData();
112
+ assert.deepEqual(initial, {
113
+ voices: [
114
+ { id: "en_US-lessac-medium", sizeMb: 63, note: "natural US English", downloaded: false, current: false },
115
+ { id: "en_GB-alba-medium", sizeMb: 63, note: "natural British English", downloaded: false, current: false },
116
+ { id: "de_DE-thorsten-medium", sizeMb: 63, note: "natural German", downloaded: false, current: false },
117
+ { id: "de_DE-thorsten-high", sizeMb: 110, note: "German, best quality", downloaded: false, current: false },
118
+ ], current: null, ttsProvider: null,
119
+ });
120
+ await writeFile(configPath, "invalid json");
121
+ assert.deepEqual(await service.conversationVoicesData(), initial);
122
+ await writeFile(configPath, JSON.stringify({ native: { tts: { provider: "other", modelPath: "/en_US-lessac-medium.onnx" } } }));
123
+ assert.deepEqual(await service.conversationVoicesData(), { ...initial, ttsProvider: "other" });
124
+ });
125
+
126
+ await run("catalog reads all three Piper directories, requires sidecars and prefers the first copy", async ({ service, dataHome, configPath }) => {
127
+ const dirs = [path.join(dataHome, "piper"), path.join(dataHome, "piper", "voices"), path.join(dataHome, "piper-voices")];
128
+ for (const dir of dirs) await mkdir(dir, { recursive: true });
129
+ const models = [
130
+ [dirs[0], "en_US-lessac-medium", 1], [dirs[1], "custom", 2 * 1024 * 1024],
131
+ [dirs[2], "third", 1], [dirs[2], "custom", 1],
132
+ ];
133
+ for (const [dir, id, bytes] of models) {
134
+ await writeFile(path.join(dir, `${id}.onnx`), Buffer.alloc(bytes));
135
+ await writeFile(path.join(dir, `${id}.onnx.json`), "{}");
136
+ }
137
+ await writeFile(path.join(dirs[0], "incomplete.onnx"), "no sidecar");
138
+ await writeFile(path.join(dirs[0], "ignored.txt"), "ignored");
139
+ const config = JSON.stringify({ native: { tts: { provider: "piper", modelPath: path.join(dirs[1], "custom.onnx") } } });
140
+ await writeFile(configPath, config);
141
+ const data = await service.conversationVoicesData();
142
+ assert.equal(data.ttsProvider, "piper");
143
+ assert.equal(data.current, "custom");
144
+ assert.equal(data.voices[0].downloaded, true);
145
+ assert.deepEqual(data.voices.slice(4), [
146
+ { id: "custom", sizeMb: 2, note: "found on disk", downloaded: true, current: true },
147
+ { id: "third", sizeMb: 0, note: "found on disk", downloaded: true, current: false },
148
+ ]);
149
+ assert.equal(await readFile(configPath, "utf8"), config);
150
+ await writeFile(configPath, JSON.stringify({ native: { tts: { provider: "piper", modelPath: "/missing/de_DE-thorsten-high.onnx" } } }));
151
+ const missingCurrent = await service.conversationVoicesData();
152
+ assert.equal(missingCurrent.current, "de_DE-thorsten-high");
153
+ assert.equal(missingCurrent.voices[3].downloaded, false);
154
+ });
155
+
156
+ await run("voice selection uses only the native command and returns the existing envelope", async ({ service, tab, calls, response, configPath, directory }) => {
157
+ const config = JSON.stringify({ native: { tts: { provider: "piper", modelPath: "/test/en_US-lessac-medium.onnx" } } });
158
+ await writeFile(configPath, config);
159
+ const data = await service.setConversationVoice(tab, { voice: " en_US-lessac-medium " });
160
+ assert.equal(data.current, "en_US-lessac-medium");
161
+ assert.equal(data.response, response);
162
+ assert.deepEqual(calls.feature, [tab]);
163
+ assert.deepEqual(calls.rpc, [[{ type: "prompt", message: "/talk voice en_US-lessac-medium" }, 600_000]]);
164
+ assert.equal(await readFile(configPath, "utf8"), config);
165
+ assert.deepEqual(await readdir(directory), ["voice.json"]);
166
+ assert.deepEqual(calls.fetch, []);
167
+ });
168
+
169
+ await run("invalid voice IDs fail before discovery or RPC", async ({ service, tab, calls }) => {
170
+ for (const voice of ["", "../voice/file", "voice with spaces", "voice\ncommand", "v".repeat(121)]) {
171
+ await assert.rejects(service.setConversationVoice(tab, { voice }), httpError(400, /Piper voice id/));
172
+ }
173
+ assert.deepEqual(calls.feature, []);
174
+ assert.deepEqual(calls.rpc, []);
175
+ assert.deepEqual(calls.fetch, []);
176
+ });
177
+
178
+ await run("voice command availability, aliases and failures retain their contracts", async ({ service, tab, calls, feature, setRpc }) => {
179
+ feature.available = false;
180
+ await assert.rejects(service.setConversationVoice(tab, { voice: "test" }), httpError(404, feature.unavailableReason));
181
+ assert.deepEqual(calls.rpc, []);
182
+ feature.available = true;
183
+ for (const [commands, expected] of [[["conversation", "voice"], "conversation"], [[], "talk"]]) {
184
+ feature.commands = commands;
185
+ await service.setConversationVoice(tab, { voice: "test" });
186
+ assert.deepEqual(calls.rpc.at(-1), [{ type: "prompt", message: `/${expected} voice test` }, 600_000]);
187
+ }
188
+ setRpc(async () => ({ success: false, error: "Companion rejected voice" }));
189
+ await assert.rejects(service.setConversationVoice(tab, { voice: "test" }), httpError(400, "Companion rejected voice"));
190
+ setRpc(async () => ({ success: false }));
191
+ await assert.rejects(service.setConversationVoice(tab, { voice: "test" }), httpError(400, "Failed to switch the conversation voice to test"));
192
+ const failure = new Error("RPC unavailable");
193
+ setRpc(async () => { throw failure; });
194
+ await assert.rejects(service.setConversationVoice(tab, { voice: "test" }), (error) => error === failure);
195
+ });
196
+
197
+ await run("status exposes provider availability and credential-free endpoint labels at call time", async ({ service, tab, mode, calls }) => {
198
+ const initial = service.naturalConversationVoiceProviderStatus();
199
+ assert.equal(initial.defaultProvider, "");
200
+ assert.deepEqual(initial.providers.map(({ id, configured }) => [id, configured]), [["local", false], ["groq", false], ["openai", false], ["cloudflare", false]]);
201
+ Object.assign(process.env, {
202
+ PI_VOICE_STT_URL: "http://test-user:test-password@localhost:1234/transcribe?token=test-query#test-fragment",
203
+ PI_VOICE_TTS_URL: "invalid endpoint", OPENAI_API_KEY: "test-openai-key", GROQ_API_KEY: "test-groq-key",
204
+ CLOUDFLARE_API_TOKEN: "test-cloudflare-key", CLOUDFLARE_ACCOUNT_ID: "test-account",
205
+ PI_VOICE_GROQ_STT_MODEL: "test-groq-model", PI_VOICE_OPENAI_STT_MODEL: "test-stt-model", PI_VOICE_OPENAI_TTS_MODEL: "test-tts-model",
206
+ });
207
+ const status = service.naturalConversationVoiceProviderStatus();
208
+ assert.equal(status.defaultProvider, "local");
209
+ assert.equal(status.providers[0].endpoint, "http://localhost:1234/transcribe");
210
+ assert.ok(status.providers.every(({ configured }) => configured));
211
+ assert.equal(status.providers[1].defaultModel, "test-groq-model");
212
+ assert.equal(status.providers[2].defaultModel, "test-stt-model");
213
+ assert.equal(status.providers[3].deferred, true);
214
+ const tts = service.naturalConversationVoiceProviderStatus("tts");
215
+ assert.equal(tts.providers[0].endpoint, "");
216
+ assert.equal(tts.providers[1].defaultModel, "test-tts-model");
217
+ for (const secret of ["test-user", "test-password", "test-query", "test-fragment", "test-openai-key", "test-groq-key", "test-cloudflare-key", "test-account"]) {
218
+ assert.ok(!JSON.stringify([status, tts]).includes(secret));
219
+ }
220
+ const unavailable = service.naturalConversationUnavailableResponse(tab, "tts");
221
+ assert.deepEqual(unavailable, {
222
+ featureId: NATURAL_CONVERSATION_FEATURE_ID, available: false,
223
+ mode: { ...mode, available: false, enabled: false, uiState: "off" }, voice: tts,
224
+ message: "Natural Conversation server-side voice fallbacks are opt-in. Configure a local endpoint or explicit hosted provider env vars; browser-native audio remains the default Web UI path.",
225
+ });
226
+ assert.deepEqual(calls.snapshot, [[tab, { available: false, enabled: false, uiState: "off" }]]);
227
+ assert.deepEqual(calls.fetch, []);
228
+ });
229
+
230
+ await run("remote consent is checked before provider selection and audio decoding", async ({ service, tab, calls }) => {
231
+ const body = {
232
+ get provider() { assert.fail("provider accessed before consent"); },
233
+ get audioBase64() { assert.fail("audio decoded before consent"); },
234
+ };
235
+ for (const consent of [undefined, false, "true", 1]) {
236
+ const requestBody = Object.create(body);
237
+ requestBody.remoteMicStreamingConsentAccepted = consent;
238
+ await assert.rejects(service.handleNaturalConversationSttTranscribe(remoteRequest, tab, requestBody), httpError(403, /explicit per-tab remote microphone streaming consent/));
239
+ }
240
+ assert.deepEqual(calls.fetch, []);
241
+ assert.deepEqual(calls.snapshot, []);
242
+ });
243
+
244
+ await run("provider selection and missing credentials fail before decode or dispatch", async ({ service, tab, calls }) => {
245
+ for (const kind of ["stt", "tts"]) {
246
+ const handle = kind === "stt" ? service.handleNaturalConversationSttTranscribe : service.handleNaturalConversationTtsSpeech;
247
+ for (const [provider, status] of [[undefined, 501], ["local", 424], ["openai", 424], ["unknown", 400], ["cloudflare", kind === "stt" ? 501 : 400], ["groq", kind === "stt" ? 424 : 400]]) {
248
+ await assert.rejects(handle(localRequest, tab, {
249
+ provider,
250
+ get audioBase64() { assert.fail("audio decoded before provider validation"); },
251
+ get text() { assert.fail("text read before provider validation"); },
252
+ }), (error) => {
253
+ assert.equal(error.statusCode, status);
254
+ if (status === 424 || provider === undefined) assert.equal(error.voice.kind, kind);
255
+ return true;
256
+ });
257
+ }
258
+ }
259
+ process.env.CLOUDFLARE_API_TOKEN = "test-cloudflare-key";
260
+ process.env.CLOUDFLARE_ACCOUNT_ID = "test-account";
261
+ await assert.rejects(service.handleNaturalConversationSttTranscribe(localRequest, tab, { provider: "cloudflare", audioBase64 }), httpError(501, /adapter is deferred/));
262
+ assert.deepEqual(calls.fetch, []);
263
+ });
264
+
265
+ await run("STT rejects empty, invalid, unsupported and oversized audio before dispatch", async ({ service, tab, calls }) => {
266
+ process.env.PI_VOICE_STT_URL = "http://local.test/stt";
267
+ for (const [body, status, message] of [
268
+ [{}, 400, /audioBase64 is required/],
269
+ [{ audioBase64: "?invalid" }, 400, /valid base64/],
270
+ [{ audioBase64: "=" }, 400, /empty audio payload/],
271
+ [{ audioBase64, mimeType: "text/plain" }, 415, /Unsupported voice audio mime type/],
272
+ [{ audioBase64: "data:text/plain;base64,YQ==" }, 415, /Unsupported voice audio mime type/],
273
+ [{ audioBase64: Buffer.alloc(audioLimit + 1).toString("base64") }, 413, /Audio payload is too large/],
274
+ ]) await assert.rejects(service.handleNaturalConversationSttTranscribe(localRequest, tab, body), httpError(status, message));
275
+ assert.deepEqual(calls.format, [audioLimit]);
276
+ assert.deepEqual(calls.fetch, []);
277
+ });
278
+
279
+ await run("local STT retains form fields, data URLs, MIME handling, filename sanitation and envelope", async ({ service, tab, mode, calls, setFetch }) => {
280
+ process.env.PI_VOICE_STT_URL = "http://local.test/stt";
281
+ setFetch(() => jsonResponse({ data: { text: " heard text " } }));
282
+ const result = await service.handleNaturalConversationSttTranscribe(localRequest, tab, {
283
+ audio: `data:audio/wav;base64, ${audioBase64}\n`, model: "local-model", language: "de", prompt: "context", fileName: "a/b\\c\0.wav",
284
+ });
285
+ assert.deepEqual(result, { provider: "local", text: "heard text", mimeType: "audio/wav", byteLength: 10, mode });
286
+ const [url, init] = calls.fetch[0];
287
+ assert.equal(url, "http://local.test/stt");
288
+ assert.equal(init.method, "POST");
289
+ assert.equal(init.headers, undefined);
290
+ assert.ok(init.signal instanceof AbortSignal);
291
+ assert.equal(init.body.get("file").name, "a_b_c_.wav");
292
+ assert.equal(init.body.get("file").type, "audio/wav");
293
+ assert.equal(await init.body.get("file").text(), "test audio");
294
+ assert.equal(init.body.get("model"), "local-model");
295
+ assert.equal(init.body.get("language"), "de");
296
+ assert.equal(init.body.get("prompt"), "context");
297
+ assert.deepEqual(calls.snapshot, [[tab, {}]]);
298
+ });
299
+
300
+ await run("STT supports consent aliases, every allowed MIME type and the exact audio size limit", async ({ service, tab, setFetch, calls }) => {
301
+ process.env.PI_VOICE_STT_URL = "http://local.test/stt";
302
+ setFetch(() => new Response(" plain transcript "));
303
+ for (const consentName of ["remoteMicStreamingConsentAccepted", "remoteMicStreamingConsent"]) {
304
+ const result = await service.handleNaturalConversationSttTranscribe(remoteRequest, tab, { audioBase64, [consentName]: true });
305
+ assert.equal(result.text, "plain transcript");
306
+ }
307
+ for (const mimeType of ["audio/webm", "audio/wav", "audio/x-wav", "audio/mpeg", "audio/mp3", "audio/mp4", "audio/ogg", "audio/flac", "application/octet-stream"]) {
308
+ await service.handleNaturalConversationSttTranscribe(localRequest, tab, { data: audioBase64, contentType: mimeType.toUpperCase(), fileName: "v".repeat(200) });
309
+ assert.equal(calls.fetch.at(-1)[1].body.get("file").name.length, 120);
310
+ }
311
+ const result = await service.handleNaturalConversationSttTranscribe(localRequest, tab, { audioBase64: Buffer.alloc(audioLimit).toString("base64") });
312
+ assert.equal(result.byteLength, audioLimit);
313
+ });
314
+
315
+ await run("hosted STT preserves provider URLs, credentials, default and overridden models", async ({ service, tab, setFetch, calls }) => {
316
+ Object.assign(process.env, { OPENAI_API_KEY: "test-openai-key", GROQ_API_KEY: "test-groq-key" });
317
+ setFetch(() => jsonResponse({ result: { text: "transcript" } }));
318
+ for (const [provider, host, model] of [["openai", "api.openai.com", "gpt-4o-mini-transcribe"], ["groq", "api.groq.com", "whisper-large-v3-turbo"]]) {
319
+ const result = await service.handleNaturalConversationSttTranscribe(localRequest, tab, { providerId: provider.toUpperCase(), audioBase64 });
320
+ assert.equal(result.provider, provider);
321
+ const [url, init] = calls.fetch.at(-1);
322
+ assert.equal(url, `https://${host}${provider === "groq" ? "/openai" : ""}/v1/audio/transcriptions`);
323
+ assert.equal(init.headers.authorization, `Bearer test-${provider}-key`);
324
+ assert.equal(init.body.get("model"), model);
325
+ assert.equal(init.body.get("response_format"), "json");
326
+ }
327
+ process.env.PI_VOICE_STT_PROVIDER = "groq";
328
+ process.env.PI_VOICE_GROQ_STT_MODEL = "env-groq";
329
+ await service.handleNaturalConversationSttTranscribe(localRequest, tab, { audioBase64 });
330
+ assert.equal(calls.fetch.at(-1)[1].body.get("model"), "env-groq");
331
+ await service.handleNaturalConversationSttTranscribe(localRequest, tab, { provider: "openai", model: "requested-model", audioBase64 });
332
+ assert.equal(calls.fetch.at(-1)[1].body.get("model"), "requested-model");
333
+ });
334
+
335
+ await run("TTS rejects missing and oversized text before provider dispatch", async ({ service, tab, calls }) => {
336
+ process.env.PI_VOICE_TTS_URL = "http://local.test/tts";
337
+ for (const body of [{}, { text: " " }]) {
338
+ await assert.rejects(service.handleNaturalConversationTtsSpeech(remoteRequest, tab, body), httpError(400, /text is required/));
339
+ }
340
+ await assert.rejects(service.handleNaturalConversationTtsSpeech(remoteRequest, tab, { text: "x".repeat(12_001) }), httpError(413, "TTS text is too long (limit 12000 characters)"));
341
+ assert.deepEqual(calls.fetch, []);
342
+ });
343
+
344
+ await run("local TTS keeps opt-in text dispatch, JSON audio variants and exact text limit", async ({ service, tab, mode, setFetch, calls }) => {
345
+ Object.assign(process.env, { PI_VOICE_TTS_URL: "http://local.test/tts", PI_VOICE_TTS_VOICE: "env-voice", PI_VOICE_TTS_FORMAT: "wav" });
346
+ setFetch(() => jsonResponse({ data: { audioBase64 }, mimeType: "audio/wav", format: "wav" }));
347
+ const result = await service.handleNaturalConversationTtsSpeech(remoteRequest, tab, { input: " hello " });
348
+ assert.deepEqual(result, { provider: "local", audioBase64, contentType: "audio/wav", format: "wav", byteLength: 10, mode });
349
+ const [url, init] = calls.fetch[0];
350
+ assert.equal(url, "http://local.test/tts");
351
+ assert.equal(init.method, "POST");
352
+ assert.deepEqual(init.headers, { "content-type": "application/json" });
353
+ assert.deepEqual(JSON.parse(init.body), { text: "hello", voice: "env-voice", format: "wav" });
354
+ setFetch(() => jsonResponse({ audio: audioBase64, contentType: "audio/ogg" }));
355
+ const overridden = await service.handleNaturalConversationTtsSpeech(localRequest, tab, { text: "x".repeat(12_000), voice: "requested-voice", format: "ogg" });
356
+ assert.equal(overridden.contentType, "audio/ogg");
357
+ assert.equal(overridden.format, "ogg");
358
+ assert.deepEqual(JSON.parse(calls.fetch.at(-1)[1].body), { text: "x".repeat(12_000), voice: "requested-voice", format: "ogg" });
359
+ });
360
+
361
+ await run("OpenAI TTS keeps defaults, environment overrides, requested fields and binary envelope", async ({ service, tab, mode, setFetch, calls }) => {
362
+ process.env.OPENAI_API_KEY = "test-openai-key";
363
+ setFetch(() => new Response(Buffer.from("audio"), { headers: { "content-type": "audio/wav" } }));
364
+ const result = await service.handleNaturalConversationTtsSpeech(remoteRequest, tab, { provider: "openai", text: " hello " });
365
+ assert.deepEqual(result, { provider: "openai", audioBase64: Buffer.from("audio").toString("base64"), contentType: "audio/wav", format: "mp3", byteLength: 5, mode });
366
+ const [url, init] = calls.fetch[0];
367
+ assert.equal(url, "https://api.openai.com/v1/audio/speech");
368
+ assert.deepEqual(init.headers, { authorization: "Bearer test-openai-key", "content-type": "application/json" });
369
+ assert.deepEqual(JSON.parse(init.body), { model: "gpt-4o-mini-tts", voice: "alloy", input: "hello", response_format: "mp3" });
370
+ Object.assign(process.env, { PI_VOICE_TTS_PROVIDER: "openai", PI_VOICE_OPENAI_TTS_MODEL: "env-model", PI_VOICE_OPENAI_TTS_VOICE: "env-voice", PI_VOICE_OPENAI_TTS_FORMAT: "flac" });
371
+ await service.handleNaturalConversationTtsSpeech(localRequest, tab, { text: "hello" });
372
+ assert.deepEqual(JSON.parse(calls.fetch.at(-1)[1].body), { model: "env-model", voice: "env-voice", input: "hello", response_format: "flac" });
373
+ await service.handleNaturalConversationTtsSpeech(localRequest, tab, { text: "hello", model: "requested-model", voice: "requested-voice", format: "wav" });
374
+ assert.deepEqual(JSON.parse(calls.fetch.at(-1)[1].body), { model: "requested-model", voice: "requested-voice", input: "hello", response_format: "wav" });
375
+ });
376
+
377
+ await run("provider HTTP failures preserve status mapping and bounded messages", async ({ service, tab, setFetch, calls }) => {
378
+ Object.assign(process.env, { PI_VOICE_STT_URL: "http://local.test/stt", PI_VOICE_TTS_URL: "http://local.test/tts" });
379
+ for (const [method, body] of [[service.handleNaturalConversationSttTranscribe, { audioBase64 }], [service.handleNaturalConversationTtsSpeech, { text: "hello" }]]) {
380
+ for (const status of [401, 429, 500, 503]) {
381
+ setFetch(() => new Response("e".repeat(900), { status }));
382
+ await assert.rejects(method(localRequest, tab, body), (error) => {
383
+ assert.equal(error.statusCode, status >= 500 ? 502 : 400);
384
+ assert.ok(error.message.endsWith("e".repeat(500)));
385
+ assert.ok(!error.message.endsWith("e".repeat(501)));
386
+ assert.match(error.message, new RegExp(`HTTP ${status}:`));
387
+ return true;
388
+ });
389
+ assert.deepEqual(calls.truncate.at(-1), ["e".repeat(900), 500]);
390
+ }
391
+ }
392
+ setFetch(() => ({ ok: false, status: 502, statusText: "Bad gateway", text: async () => { throw new Error("unreadable"); } }));
393
+ await assert.rejects(service.handleNaturalConversationSttTranscribe(localRequest, tab, { audioBase64 }), httpError(502, "local STT voice provider returned HTTP 502: Bad gateway"));
394
+ });
395
+
396
+ await run("provider parse and transport failures propagate without changing envelopes", async ({ service, tab, setFetch }) => {
397
+ Object.assign(process.env, { PI_VOICE_STT_URL: "http://local.test/stt", PI_VOICE_TTS_URL: "http://local.test/tts" });
398
+ for (const [response, message] of [[() => jsonResponse({ unexpected: "missing" }), /JSON without a transcript text field/], [() => new Response(" "), /empty transcript/]]) {
399
+ setFetch(response);
400
+ await assert.rejects(service.handleNaturalConversationSttTranscribe(localRequest, tab, { audioBase64 }), httpError(502, message));
401
+ }
402
+ for (const [response, message] of [[() => jsonResponse({ unexpected: "missing" }), /JSON without audioBase64/], [() => new Response(new Uint8Array()), /empty audio/]]) {
403
+ setFetch(response);
404
+ await assert.rejects(service.handleNaturalConversationTtsSpeech(localRequest, tab, { text: "hello" }), httpError(502, message));
405
+ }
406
+ const transportError = new Error("Synthetic fetch failure");
407
+ setFetch(() => { throw transportError; });
408
+ await assert.rejects(service.handleNaturalConversationSttTranscribe(localRequest, tab, { audioBase64 }), (error) => error === transportError);
409
+ await assert.rejects(service.handleNaturalConversationTtsSpeech(localRequest, tab, { text: "hello" }), (error) => error === transportError);
410
+ setFetch(() => new Response("{broken", { headers: { "content-type": "application/json" } }));
411
+ await assert.rejects(service.handleNaturalConversationSttTranscribe(localRequest, tab, { audioBase64 }), SyntaxError);
412
+ await assert.rejects(service.handleNaturalConversationTtsSpeech(localRequest, tab, { text: "hello" }), SyntaxError);
413
+ });
414
+
415
+ await run("timeout is captured at module load, clamped to 1000ms and passed to both providers", async ({ service, tab, setFetch }) => {
416
+ Object.assign(process.env, { PI_VOICE_STT_URL: "http://local.test/stt", PI_VOICE_TTS_URL: "http://local.test/tts" });
417
+ setFetch((_url, { signal }) => new Promise((_resolve, reject) => {
418
+ const guard = setTimeout(() => reject(new Error("Provider did not receive the captured timeout")), 2_000);
419
+ signal.addEventListener("abort", () => { clearTimeout(guard); reject(signal.reason); }, { once: true });
420
+ }));
421
+ await Promise.all([
422
+ assert.rejects(service.handleNaturalConversationSttTranscribe(localRequest, tab, { audioBase64 }), { name: "TimeoutError" }),
423
+ assert.rejects(service.handleNaturalConversationTtsSpeech(remoteRequest, tab, { text: "hello" }), { name: "TimeoutError" }),
424
+ ]);
425
+ });
426
+ });